抽象类
简介
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图。
其中,柱体类提供计算体积的方法。平面图形类提供计算底图面积的方法。圆类和长方体类从平面图形类中派生,他们提供具体底图。
结语
人生漫长,晴雨交加,但若是心怀热爱,即使岁月荒芜,亦能奔山赴海,静待一树花开。