对面向抽象编程的理解

面向抽象编程是什么,第一遍看的时候没太注意,感觉的不是很重要吧,可当我去细看时,面向抽象的功能作用竟如此强大,我是应该再好好总结一下的。

面向抽象编程,顾名思义,是对抽象类(abstract)进行一系列操作的编程。也就是说 当设计某种重要的类时,不让该类面向具体的类,而是面向抽象类,即 设计类中的重要数据 是 抽象类的对象 ,不是具体类声明的对象。

简单一点理解,就是定义了一个abstract类 和 一个abstract 方法,再定义一个或几个abstract类的子类,在子类中重写abstract类中的abstract方法(子类中重写的方法不再是abstract方法),然后就可以只声明一个abstract类,再利用 上转型对象 对其重写的方法进行调用。这样就可以实现声明的一个变量可以应对多种不同的变化。 

来看一个实例的应用:(求柱体体积)

 abstract类及其子类:

public abstract class Geometry {
    public abstract double getArea();//只是单纯的构造了一个abstract方法,不用加任何东西。
}

class Circle extends Geometry{
    double r;
    Circle(double r){//构造函数
        this.r = r;
    }
    public double getArea() {   / /方法的重写
        return r * r * 3.14;
    }
}
class Rectangle extends Geometry{
    double a,b;
    Rectangle(double a,double b){
        this.a = a;
        this.b = b;
    }
    public double getArea() {
        return a*b;
    }
}

获取柱体体积的类,不再依赖具体类,而是面向Geometry类:

public class Pillar {

    Geometry bottom;//声明Geometry对象(抽象对象)
    double hight;
    Pillar(Geometry bottom,double h){//构造函数,获取值
        this.bottom = bottom;
        this.hight = h;
    }
    
    public double getVolume(){//返回体积值
        if(bottom == null){
            System.out.println("没有底,无法计算面积");
            return 0;
        }
        return bottom.getArea()*hight;//这里的调用的getArea()函数根据对bottom的上转型对象来确定。
    }
}

创建上转型对象,确定其调用函数,输出其值

public class Application {

    public static void main(String[] args) {
        Pillar pillar;
        Geometry bottom;
        
        bottom = null;
        pillar = new Pillar(bottom,5);
        System.out.println("体积:" + pillar.getVolume());
        
        bottom = new Circle(2);//上转型对象
        pillar = new Pillar(bottom,1);
        System.out.println("体积:" + pillar.getVolume());//调用的是Circle里面的getVolume()。
        
        bottom = new Rectangle(5,2);//上转型对象
        pillar = new Pillar(bottom,1);
        System.out.println("体积:" + pillar.getVolume());//调用的是Rectangle里面的getVolume()。
    }
}

面向抽象编程的目的是为了应对用户需求的变化,将某个类中经常因需求变化需要改动的代码分离出去。

面向抽象编程的核心是让类中每种可能的变化对应的交给抽象类的一个子类去负责,从而让类的设计者不再去关心具体的实现。

 

猜你喜欢

转载自blog.csdn.net/weixin_42227243/article/details/82914929