展开全部
在main方法中实现Shape的对象时,使用Trangle或者Rectangle分别进行实例化。这样对于同一个Pillar的对象,可以调用两个不同类的32313133353236313431303231363533e4b893e5b19e31333365633838实现方法来计算。具体代码请参考下面。
Shape.javapublic abstract class Shape {
public int dim1;
public int dim2;
public abstract int getArea();
}
Trangle.javapublic class Trangle extends Shape {
public int getArea() {
return (super.dim1 * super.dim2) / 2;
}
}
Rectangle.javapublic class Rectangle extends Shape {
public int getArea() {
return super.dim1 * super.dim2;
}
}
Pillar.javapublic class Pillar {
public Shape shape;
public int height;
public int getVolumn() {
return this.shape.getArea() * this.height;
}
public static void main(String[] args) {
// 三棱柱
Pillar p = new Pillar();
p.shape = new Trangle();
p.shape.dim1 = 2;
p.shape.dim2 = 4;
p.height = 3;
System.out.println("三棱柱的体积是:" + p.getVolumn());
// 四棱柱
p.shape = new Rectangle();
p.shape.dim1 = 2;
p.shape.dim2 = 4;
p.height = 3;
System.out.println("四棱柱的体积是:" + p.getVolumn());
}
}
下面是执行后的结果: