JAVA: 面向对象编程 (天天向上系列)

所谓面向抽象编程是指当设计某种重要的类时,不让该类面向具体的类,而是面向抽象类,及所设计类中的重要数据是抽象类声明的对象,而不是具体类声明的对象。就是利用abstract来设计实现用户需求。



Pillar 面向 对象设计,  柱体, 只负责计算 体积.

一个柱体在计算底面积是不应该关心他的底是社么形状的具体图案,应该只关心这种图像是否具有计算出面积的方法。因此,在设计Pillar(柱类)的时候不应当让他的底是某个具体类的声明的对象,一旦这么做,Pillar(柱类)就会依赖具体类,缺乏弹性,难以应对需求的变化。

第一步:定义一个抽象类Geometry,类中定义一个抽象的getArea()方法

public abstract class Geometry {
    public abstract double getArea();
}

第二步:Pillar(柱类)可以面向Geometry类编写代码,即Pillar(柱类)应当把Geometry类作为自己的成员,该成员可以调用Geometry的子类重写的getArea()方法。这样,Pillar(柱类)就将计算底面积的任务指派个Geometry类的子类的实例,不再依赖于某一个具体的类,而是面向Geometry类的,即Pillar(柱类)的bottom是用抽象类Geometry声明的对象,而不是具体的某一类,新的Pillar(柱类)如下:

public class Pillar {
    Geometry bottom;
    private  double height;
    Pillar(Geometry bottom,double height){
        this.bottom = bottom;
        this.height = height;
    }
    public double getVolume(){
        return bottom.getArea()*this.height;
    }
}

增加Geometry的子类时就不需要修改Pillar(柱类)的任何代码,

public class Rectangle extends Geometry {
    private double a,b;
    Rectangle(double a,double b){
        this.a = a;
        this.b = b;
    }
    @Override
    public double getArea() {
        return a*b;
    }
}
public class Circle extends Geometry {
    private  double r;
    Circle(double r){
        this.r = r;
    }
    @Override
    public double getArea() {
        return Math.PI*r*r;
    }
}

应用 TEST

import java.util.Scanner;

public class Main {

    public static void main(String[] args){
        Pillar pillar ;
        Geometry bottom;
        bottom = new Circle(10);
        pillar = new Pillar(bottom,10);
        System.out.println("圆柱体体积: "+pillar.getVolume());
        bottom = new Rectangle(4,5);
        pillar = new Pillar(bottom,10);
        System.out.println("长方体体积: "+pillar.getVolume());
    }
}


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值