案例: 定义两个类,父类GeometricObject代表几何形状,子类Circle代表圆形。 写一个测试类,创建两个Circle对象,判断其颜色是否相等;利用equals方法判断其半径是否相等; 利用toString()方法输出其半径。
package chapter07_oop2.src.com.atguigu07.object.tostring.exer; /** * ClassName: Circle * Description: * * @Author 尚硅谷-宋红康 * @Create 11:41 * @Version 1.0 */ public class Circle extends GeometricObject{ private double radius; public Circle() { // color = "white"; // weight = 1.0; radius = 1.0; } public Circle(double radius) { // color = "white"; // weight = 1.0; this.radius = radius; } public Circle(String color, double weight, double radius) { super(color, weight); this.radius = radius; } public double getRadius() { return radius; } public void setRadius(double radius) { this.radius = radius; } //求圆的面积 public double findArea(){ return 3.14 * radius * radius; } //重写equals() public boolean equals(Object obj){ if(this == obj){ return true; } if(obj instanceof Circle){ Circle c = (Circle) obj; return this.radius == c.radius; } return false; } //重写toString() @Override public String toString() { return "Circle[radius = " + radius + "]"; } }
package chapter07_oop2.src.com.atguigu07.object.tostring.exer; /** * ClassName: CircleTest * Description: * 写一个测试类,创建两个Circle对象,判断其颜色是否相等;利用equals方法判断其半径是否相等; * 利用toString()方法输出其半径。 * @Author 尚硅谷-宋红康 * @Create 11:47 * @Version 1.0 */ public class CircleTest { public static void main(String[] args) { Circle c1 = new Circle(2.3); Circle c2 = new Circle("red",2.0,3.4); System.out.println("颜色是否相等?" + c1.getColor().equals(c2.getColor())); System.out.println("半径是否相等?" + c1.equals(c2)); System.out.println(c1); System.out.println(c1.toString()); } }
package chapter07_oop2.src.com.atguigu07.object.tostring.exer; /** * ClassName: GeometricObject * Description: * * @Author 尚硅谷-宋红康 * @Create 11:40 * @Version 1.0 */ public class GeometricObject { protected String color; protected double weight; public GeometricObject() { color = "white"; weight = 1.0; } public GeometricObject(String color, double weight) { this.color = color; this.weight = weight; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public double getWeight() { return weight; } public void setWeight(double weight) { this.weight = weight; } }