首页 > 其他 > 详细

2、实体类和接口的问题

时间:2021-03-08 09:26:19      阅读:18      评论:0      收藏:0      [点我收藏+]
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());  
    }
}

 

2、实体类和接口的问题

原文:https://www.cnblogs.com/heijiaoshou/p/14496998.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!