下面是原代码
abstract class TwoDShape { // 定义抽象类
private double width;
private double height;
private String name;
TwoDShape() {
width = height = 0.0;
name = "null";
}
TwoDShape(double w, double h, String n) {
width = w;
height = h;
name = n;
}
TwoDShape(double x, String n) {
width = height = x;
name = n;
}
TwoDShape(TwoDShape ob) {
width = ob.width;
height = ob.height;
name = ob.name;
}
double getWidth() {
return width;
}
double getHeight() {
return height;
}
void setWidth(double w) {
width = w;
}
void setHeight(double h) {
height = h;
}
String getName() {
return name;
}
void showDim() {
System.out.println("Width and height are "+width+" and "+height);}
abstract double area();
} // end class TwoDShape
class Triangle extends TwoDShape { // Triangel 是抽象类 TwoDShape的子类
private String style;
Triangle() {
super();
style = "null";
}
Triangle(String s, double w, double h) {
super(w, h, "triangle");
style = s;
}
Triangle(double x) {
super(x, "triangle");
style = "isosceles";
}
Triangle(Triangle ob) {
super(ob);
style = ob.style;
}
double area() {
return getWidth() * getHeight() / 2;
}
void showStyle() {
System.out.println("Trangle is " + style);
}
} // end class TwoDShape
class Rectangle extends TwoDShape { // Rectangle是抽象类的子类
Rectangle() {
super();
}
Rectangle(double w, double h) {
super(w, h, "retangle");
}
Rectangle(double x) {
super(x, "rectangle");
}
Rectangle(Rectangle ob) {
super(ob);
}
boolean isSquare() {
if (getWidth() == getHeight())
return true;
else
return false;
}
double area() {
return getWidth() * getHeight();
}
} // end class Rectangle
public class AbstractDemo {
public static void main(String [ ] args) {
TwoDShape shapes[ ] =new TwoDShape[4]; // ? shapes[ ]
shapes[0] = new Triangle("right",8.0,12.0);
shapes[1] = new Rectangle(10);
shapes[2] = new Rectangle(10,4);
shapes[3] = new Triangle(7.0);
for(int i = 0; i < shapes.length;i++){
System.out.println("object is " + shapes[i].getName());
System.out.println("Area is " + shapes[i].area());
System.out.println();
}
}
} // end class AbstractDemo
疑问:ob不应该是引用Triangle的对象吗Triangle(Triangle ob) { super(ob); },为什么又在这TwoDShape(TwoDShape ob)
是上转型还是什么呢