Java面向抽象编程的思想

在设计程序时,经常会使用abstract类,其原因是,abstract类只关心操作,但不关心这些操作具体实现的细节,可以是程序的设计者把主要精力放在程序的设计上,而不必拘泥于细节的实现,既避免设计者把大量的时间和经理花费在具体的算法上。
在设计一个程序时,可以通过在abstract类中声明若干个abstract方法,表明这些方法在整个系统设计中的重要性,方法体的内容细节有它的abstract子类去完成。
使用多态进行程序设计的核心技术之一是使用上转型对象,即将abstract类声明对象作为其子类的上传型对象,那么这个上转型对象就可以调用子类重写的方法。
所谓面向抽象编程,是指当设计一个类时,不让该类面向具体的类,而是面向抽象类,即所设计类中的重要数据是抽象类声明的对象,而不是具体类声明的对象。
示例:

abstract class Geometry{
    public abstract double getArea();//模块
}
class Circle extends Geometry{
    double r;
    Circle(double r){
        this.r=r;
    }
    public double getArea(){//交给子类实现具体算法
        return (3.14*r*r);
    }
}
class Rectangle extends Geometry{
    double a,b;
    Rectangle(double a,double b){
        this.a=a;
        this.b=b;
    }
    public double getArea(){
        return (a*b);
    }
}
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 App{
    public static void main(String [] args){
        Pillar pillar;
        Geometry bottom;
        bottom = new Rectangle(12,22);
        pillar = new Pillar(bottom,58);//pillar是具有矩形底的柱体
        System.out.println("矩形底的柱体的体积"+pillar.getVolume());
        bottom = new Circle(10);//当用户需求改变时,不需要更改系统核心模块
        pillar = new Pliiar(bottom,58);//pillar是具有圆形底的柱体
        System.out.println("圆形底的柱体的体积"+pillar.getVolume());
    }
}

实现系统易维护:
开-闭原则,让设计的系统应用应当对扩展开放,对修改关闭。当系统中增加新的模块式,不需要修改现有模块。
在设计系统时,应当首先考虑到用户需求的变化,将应对用户变化的部分设计为扩展开放,而设计核心部分是经过精心考虑之后确定基本结构,应当对修改关闭。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值