# 不能理解的java代码“Triangle(Triangle ob) { super(ob); }”

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

• 写回答

#### 4条回答默认 最新

• 关注

子类可以直接转换为父类，只要是TwoDShape类的子类传进来的对象都可以接收。抽象类是介于接口和类之间的，这样定义的目的就是可以让TwoDShape类的任何子类都可以当做参数传进来初始化父类，而不用定义多个方法。

本回答被题主选为最佳回答 , 对您是否有帮助呢?
评论

#### 悬赏问题

• ¥15 数据结构中的数组地址问题
• ¥15 LD衰减怎么根据纵坐标计算横坐标的值
• ¥15 maya的mel里，怎样先选择模型A，然后利用mel脚本自动选择有相同名字的模型B呢。
• ¥15 Python题，根本不会啊
• ¥15 会会信号与系统和python的来
• ¥15 关于#python#的问题
• ¥20 oracle RAC 怎么配置啊，配置
• ¥15 excel 日常使用中出现问题
• ¥20 pdusession建立失败
• ¥15 为什么mqtt接收不到数据？