package e; interface Geometry{//设计接口,包含方法getArea(); public double getArea(); } class Pillar{ Geometry bottom;//底面接口 double height; public Pillar(Geometry bottom, double height){//带参构造方法 //赋值操作 this.bottom=bottom; this.height=height; }//创建成员方法,计算体积 public double Volume(){ return bottom.getArea()*this.height; } } class Circle implements Geometry{ //创建圆形类 double radius; public Circle(double radius){ //调用本类成员变量 this.radius = radius; } public double getArea() { //重写接口方法 return Math.PI*this.radius*this.radius; } } class Rect implements Geometry{ //创建矩形类 double wide,length; public Rect(double wide, double length){//调用本类成员变量 this.wide = wide; this.length = length; } public double getArea() {//重写接口方法 return wide*length; } } public class shangji_03 { public static void main(String[] args) { //创建对象 Pillar pillar; Geometry bottom; bottom = new Rect(10, 5); pillar = new Pillar(bottom, 5); System.out.println("矩形底的柱体的体积:" + pillar.Volume()); bottom = new Circle(5); pillar = new Pillar(bottom, 5); System.out.println("圆形底的柱体的体积:" + pillar.Volume()); } }
原文:https://www.cnblogs.com/heijiaoshou/p/14496998.html