如何理解抽象类?
举个例子,比如创建的母类名为“Shape”,它有子类“Circle”和“Rectangle”。
母类定义了一个方法叫“drawMe()”,“画我”。
然而圆和正方形都可以画出来,但是他们的母类,并不拥有一个能够画出来的具体形状。
因此,母类的drawMe()
无意义。
但是作为要被子类继承的一种方法,它必须存在。这时我们就可以将母类定义为
“抽象类”
"abstract class"
,
并将其中的方法定义为
“抽象方法” "abstract method"。
抽象类在此只作为:
- Placeholder
- 把method细节留给子类method处理。
- 体现泛用概念。
此方法远优于:
- 画一些“未定义的形状”。
- 直接忽视母类drawMe()的存在。
- throw exception弹出error message终止运行。
- 让系统报错。
Example:
母类 superclass:
public abstract class Shape {
private String color;
public Shape(String color) { // OK to have constructor as a constructor
this.color = color; // initializes color part
}
public String getColor() {
return color;
}
public abstract void drawMe();
}
子类 subclass:
public class Rectangle extends Shape {
private int width, length;
public Rectangle(String color, int width, int length) {
super(color);
this.width = width;
this.length = length;
}
public void drawMe() {
System.out.println("Drawing Rectangle with dimensions (W/L) ");
System.out.println(width + " " + length);
}
}
public class Circle extends Shape {
private int radius;
public Circle(String color, int radius) {
super(color);
this.radius = radius;
}
public void drawMe() {
System.out.println("Drawing Circle with radius " + radius);
}
}
Driver:
import withAbstractClass.Shape;
public class Driver {
public static void main(String[] args) {
int numberOfShapes = 2;
Shape[] allShapes = new Shape[numberOfShapes];
allShapes[0] = new Circle("Red", 10);
allShapes[1] = new Rectangle("Blue", 15, 20);
for (int i = 0; i < allShapes.length; i++) {
allShapes[i].drawMe();
}
/* No longer possible
Shape s = new Shape("Green");
s.drawMe();
*/
}
}
运行Driver.java后输出为:
Drawing Circle with radius 10
Drawing Rectangle with dimensions (W/L)
15 20