关于面对抽象编程的一些初步理解

来源:互联网 发布:网站备案 域名备案 编辑:程序博客网 时间:2024/06/10 02:41

对程序的解读:

首先定义一个抽象类Geometry,底面不确定为什么形状,定义抽象方法用于求底面的面积,抽象方法,只能声明,不能实现

public abstract double getArea();

然后定义一个非抽象的类Pillar,采用构造方法,传入两个参数,第一个为抽象类求得的面积方法,(需要定义抽象类的子类,重写抽象方法),另一个是柱体的高

接下来定义求柱体体积的方法

定义抽象类的两个子类,分别为Circle和Rectangle

重写抽象方法

定义Application类,进行测试

main类中,为Geometry创建对象bottom,创建它的上转型对象

bottom = new Circle(3);

创建对象Pillar pillar = new Pillar(bottom,6)

三角形底流程类似,自行理解

public abstract class Geometry {public abstract double getArea();}public class Pillar {Geometry bottom;double height;//构造方法Pillar(Geometry bottom,double height){this.bottom = bottom;this.height = height;}//求体积public double getVolume(){return bottom.getArea()*height;}}public class Circle extends Geometry {double r;    Circle (double r)    {    this.r = r;    }public double getArea(){return 3.14*r*r;}}public class Rectangle extends Geometry{double a,b;Rectangle(double a,double b){this.a = a;this.b = b;}public double getArea(){return a*b;}}public class Applacation {public static void main(String[] args) {Pillar pillar;Geometry bottom;bottom = new Rectangle(3,4);pillar = new Pillar(bottom,5);//柱体两个参数,一个为地面的面积,一个为高System.out.println("地面为三角形的柱体体积为:"+pillar.getVolume());bottom = new Circle(3);pillar = new Pillar(bottom,5);System.out.println("地面为圆形的柱体的体积为:"+pillar.getVolume());}}


原创粉丝点击