抽象类和面向抽象的思维——

抽象类

简介

abstract修饰符可以用来修饰方法也可以用来修饰类,如果修饰方法,那么该方法就是抽象方法;如果修饰类,那么该类就是抽象类。

  • 抽象类中可以没有抽象方法,但是有抽象方法的类一定要声明为抽象类。
  • 抽象类,不能使用new关键字来创建对象,它是用来让子类继承的。
  • 抽象方法,只有方法的声明,没有方法的实现,它是用来让子类实现的
  • 子类继承抽象类,那么就必须要实现抽象类的没有实现的抽象方法,否则该子类也要声明为抽象类
  • 抽象类可以有static、final成员。
package com.oop.Rew;
abstract class A0 {
    abstract int sum(int x,int y);
    int sub(int x,int y) {
        return x-y;
    }
}
class B extends A0 {
    int sum(int x,int y) {   //子类必须重写父类的sum方法
        return x+y;
    }
}
public class Example09 {
    public static void main(String[] args) {
        B b=new B();
        int sum=b.sum(30,20);           //调用重写的方法
        int sub=b.sub(30,20);           //调用继承的方法
        System.out.println("sum="+sum);
        System.out.println("sum="+sub);
    }
}

面向抽象编程的思维

在面向对象的设计过程中,类的设计是一个抽象的过程,不断的抽象形成类的层次结构。父类代表一般的抽象概念和行为,具有比子类更稳定的结构。面向抽象的编程,就是利用抽象类设计新的类。

比如柱体类的设计:柱体有长方体、圆柱体等不同的底图形态,这些底图可以抽象为平面图形。

设计柱体类时不需要针对各种具体的底图形态,而是直接面向其抽象的父类:平面图形。

那么这个柱体类就是面向抽象的类,它比面向长方形、圆形等具体的图形设置的类具有更好的扩展性,结构更加的稳定。

面向抽象设计的类结构稳定,并能适应各种变化,这样的类形成软件的基本结构和核心框架。

下面我们给出一个例子:

//柱体的体积 = 底面积 * 高
public class Example10 {
    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 Pillar (bottom,58); //pillar是具有圆形底的柱体
        System.out.println("圆形底的柱体的体积"+pillar.getVolume());
    }
}
//Geometry:底图,抽象类
public abstract class Geometry {
    public abstract double getArea();
}
//Pillar:面向抽象的类,抽象类Geometry是其成员
public class Pillar {
    Geometry  bottom;        //bottom是抽象类Geometry声明的变量
    double height;
    Pillar (Geometry bottom,double height) {
        this.bottom=bottom; this.height=height;
    }
    public double getVolume() {
        return bottom.getArea()*height; //bottom可以调用子类重写的getArea方法
    }
}

Geometry和Pillar构成稳定的核心框架。

//Circle:圆
public class Circle extends Geometry {
    double r;
    Circle(double r) {
        this.r=r;
    }
    public double getArea() {
        return(3.14*r*r);
    }
}
//Rectangle:长方形
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;
    }
}

Circle和Rectangle构成扩展部分,实现抽象类。

我们看一下设计的UML图。

请添加图片描述

其中,柱体类提供计算体积的方法。平面图形类提供计算底图面积的方法。圆类和长方体类从平面图形类中派生,他们提供具体底图。

结语

人生漫长,晴雨交加,但若是心怀热爱,即使岁月荒芜,亦能奔山赴海,静待一树花开。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值