在了解抽象类和抽象方法前,我们先来看一个多态的例子:
public class Shape {
private String type;
public Shape(String type) {
this.type = type;
}
public void getArea() {
System.out.println("get shape area === 0");
}
public void getType() {
System.out.println("shape type is " + type);
}
}
public class Square extends Shape {
private int length;
private int width;
public Square(String type, int length, int width) {
super(type);
this.length = length;
this.width = width;
}
@Override
public void getArea() {
int area = length * width;
System.out.println("get square area === " + area);
}
}
public class Circle extends Shape {
private int radius;
public Circle(String type, int radius) {
super(type);
this.radius = radius;
}
@Override
public void getArea() {
double area = radius * radius * 3.14;
System.out.println("get circle area === " + area);
}
}
public static void main(String[] args) {
Shape shape = new Shape("shape");
shape.getArea();
Shape square = new Square("square", 4, 2);
square.getArea();
Shape circle = new Circle("circle", 3);
circle.getArea();
}
get shape area === 0
get square area === 8
get circle area === 28.26
上述例子中,将几何形状定义为基类 Shape ,将矩形 Square 和 圆形 Circle 作为其导出类,通过对 getArea() 方法传入不同类型的对象,执行不同的方法行为,从而达到多态的目的。
我们注意到,基类 Shape 中的 getArea() 几乎没有任何意义,在实际应用过程中通常需要指定具体的几何类型(导出类)。
所以,我们并不想让其他人直接调用 Shape 类中的 getArea()方法,但仍想保留多态的特性。此时,可以将基类中的 getArea() 方法定义为抽象方法。
定义抽象方法的形式也非常简单:只需在方法名前加上 abstract 关键字即可,抽象方法内不能书写任何具体的代码。但需要注意的是,一旦类中包含一个抽象方法,此类必须强制定义为抽象类,需要在 class 关键字前加上 abstract 关键字,表示这是一个抽象类。
public abstract class Shape {
private String type;
public Shape(String type) {
this.type = type;
}
public abstract void getArea();
public void getType() {
System.out.println("shape type is " + type);
}
}
被定义为抽象的方法在导出类中强制要求其重写,不能直接被复用。
此外,抽象类也不允许被实例化。
抽象类中的非抽象方法,仍可以通过继承直接使用。
public static void main(String[] args) {
Shape square = new Square("square", 4, 2);
square.getArea();
square.getType();
Shape circle = new Circle("circle", 3);
circle.getArea();
circle.getType();
}
get square area === 8
shape type is square
get circle area === 28.26
shape type is circle
小结
定义抽象类,可以阻止的基类对象被创建;定义抽象方法,可以强制要求导出类重写方法。
本次分享至此结束,希望本文对你有所帮助,若能点亮下方的点赞按钮,在下感激不尽,谢谢您的【精神支持】。
若有任何疑问,也欢迎与我交流,若存在不足之处,也欢迎各位指正!