废话不多说,题来!
GeometriceObject 类:
package com.it18;
/*
* 该类代表几何形状
*/
public class GeometriceObject {
protected String color;
protected double weight;
public GeometriceObject() {
super();
}
public GeometriceObject(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;
}
//不知道写声明,就先返回0.0
public double findArea() {
return 0.0;
}
}
Circle 类:
package com.it18;
/*
* 此类代表圆形
*/
public class Circle extends GeometriceObject{
private double radius;
public Circle() {
super();
}
//父类中的属性,使用super();
public 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 Math.PI*radius*radius;
}
}
MyRectangle 类:
package com.it18;
/*
* 此类代表矩形
*/
public class MyRectangle extends GeometriceObject{
private double width;
private double height;
public MyRectangle() {
super();
}
//问题3:使用super(),回父类构造器中调用
public MyRectangle(double width, double height, String color, double weight) {
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;
}
}
GeometriceTest 测试类:
package com.it18;
public class GeometriceTest {
public static void main(String[] args) {
//创建本类的对象,调用本类的方法
GeometriceTest test = new GeometriceTest();
//创建圆的对象
Circle c1 = new Circle(1, "white", 1.0);
test.displayGeometriceObject(c1);
Circle c2 = new Circle(2, "white", 1.0);
test.displayGeometriceObject(c2);
boolean equalsArea = test.equalsArea(c1, c2);
System.out.println("c1和c2的面积是否相等:" + equalsArea);
/*
* 矩形的方法和圆一样,自行练习
*/
}
public void displayGeometriceObject(GeometriceObject o) {//多态:GeometriceObject o = new Circle(...);
System.out.println("面积为:" + o.findArea());
}
public boolean equalsArea(GeometriceObject o1, GeometriceObject o2) {
return o1.findArea() == o2.findArea();
}
}
总结:
该练习遇到的问题:
- 不熟悉子类调用父类的构造器。
- 遇到不明返回值的方法,不知道怎么办。
- 对多态性的理解不够,甚至题都有点看不懂。
加油吧...