c instanceof B:左边是对象,右边是类,如果创建c的类是B或者B的子类,那么返回True,可以向下转型
比如:C是B的子类,B是A的子类,①A c = new C(); 那么②B c = (B)c;就是将A类型的c向下转型为B了,因为创建对象的时候加载的是C类,而AB都是C的父类,所以AB中使用的方法,在加载中都有,都可以使用,所以可以转型
#是protected的意思
package com.instanceOf.java;
public class GeometricObject {
protected String color;
protected double weight;
public GeometricObject(String color, double weight) {
super();
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;
}
public double findArea() {
return 0;
}
}
package com.instanceOf.java;
public class Circle extends GeometricObject{
private double 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 radius*radius*Math.PI;
}
}
package com.instanceOf.java;
public class MyRectangle extends GeometricObject{
private double width;
private double height;
public MyRectangle(String color, double weight, double width, double height) {
super(color, weight);
this.width = width;
this.height = height;
}
public double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public double findArea() {
return width*height;
}
}
package com.instanceOf.java;
public class GeomatricTest {
public static void main(String[] args) {
GeomatricTest test = new GeomatricTest();
Circle c1 = new Circle("red",100,1);
MyRectangle rec = new MyRectangle("red",100,1,4);
boolean isEquals = test.equalsArea(c1,rec);
if(isEquals) {
System.out.println("面积相等");
}else {
System.out.println("面积不等");
}
test.displayGeometricObject(c1);
test.displayGeometricObject(rec);
}
public boolean equalsArea(GeometricObject c,GeometricObject rec) {
return (c.findArea() == rec.findArea());
}
public void displayGeometricObject(GeometricObject geo) {
System.out.println(geo.findArea());
}
}