课后小练习
定义三个类,父类GeometricObject代表几何形状,子类Circle代表圆形,MyRectangle代表矩形。
定义一个测试类GeometricTest,编写equalsArea方法测试两个对象的面积是否相等(注意方法的参 数类型,利用动态绑定技术),
编写displayGeometricObject方法显示对象的面积(注意方法的参 数类型,利用动态绑定技术)。
GeometricObject类的代码:
public class GeometricObject {
protected String color;
protected double weight;
protected GeometricObject(String color,double weight){
super();
this.color = color;
this.weight = weight;
}
/*public GeometricObject() {
super();
}*/
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.0;
}
}
Circle类的代码:
public class Circle extends GeometricObject {
private double radius;
protected Circle(double radius,String color, double weight) {
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;
}
}
MyRectangle类的代码
public class MyRectangle extends GeometricObject{
private double width;
private double hight;
protected MyRectangle(double width,double hight,String color, double weight) {
super(color, weight);
this.width = width;
this.hight =hight;
}
public double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
public double getHight() {
return hight;
}
public void setHight(double hight) {
this.hight = hight;
}
public double findArea(){
return width*hight;
}
}
GeometricTest的代码
/*
* 编写equalsArea方法测试两个对象的面积是否相等(注意方法的参
数类型,利用动态绑定技术),编写displayGeometricObject方法显示对象的面积(注意方法的参
数类型,利用动态绑定技术)。
*
*
*/
public class GeometricTest {
public static void main(String[] args) {
GeometricTest test = new GeometricTest();
Circle c1 = new Circle(2.3, "red", 1.0);
Circle c2 = new Circle(3.3, "red", 1.0);
test.displayGeometricObject(c1);
test.displayGeometricObject(c2);
boolean isEquals = test.equalsArea(c1,c2);
System.out.println("c1和c2面积是否相等:" + isEquals);
}
//测试对象面积是否相等
public boolean equalsArea(GeometricObject o1,GeometricObject o2){
return o1.findArea() == o2.findArea();
}
public void displayGeometricObject(GeometricObject o){//GeometricObject o = new Circle(....) 多态
System.out.println("面积为:" + o.findArea());
}
}