Java abstract class/method——抽象类/方法的应用

如何理解抽象类?

举个例子,比如创建的母类名为“Shape”,它有子类“Circle”和“Rectangle”。
母类定义了一个方法叫“drawMe()”,“画我”。
然而圆和正方形都可以画出来,但是他们的母类,并不拥有一个能够画出来的具体形状。
因此,母类的drawMe() 无意义
但是作为要被子类继承的一种方法,它必须存在。这时我们就可以将母类定义为 “抽象类” "abstract class" 并将其中的方法定义为 “抽象方法” "abstract method"。
抽象类在此只作为:
  1. Placeholder
  2. 把method细节留给子类method处理。
  3. 体现泛用概念。
此方法远优于:
  1. 画一些“未定义的形状”。
  2. 直接忽视母类drawMe()的存在。
  3. throw exception弹出error message终止运行。
  4. 让系统报错。
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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值