首选以下场景中的抽象基类:
基类不能与子类一起存在=>基类只是抽象的,不能实例化。
基类不能具有方法的完整或具体实现=>方法的实现是基类是不完整的,只有子类可以提供完整的实现。
基类为方法实现提供了一个模板,但它仍然依赖于Concrete类来完成方法实现 - Template_method_pattern
一个简单的例子来说明上述观点
Shape是抽象的,没有像Rectangle这样的混凝土形状就不能存在。 由于不同的形状具有不同的公式,因此无法在Shape类中实现绘制Shape 。 处理场景的最佳选择:将draw()实现留给子类
abstract class Shape{
int x;
int y;
public Shape(int x,int y){
this.x = x;
this.y = y;
}
public abstract void draw();
}
class Rectangle extends Shape{
public Rectangle(int x,int y){
super(x,y);
}
public void draw(){
//Draw Rectangle using x and y : length * width
System.out.println("draw Rectangle with area:"+ (x * y));
}
}
class Triangle extends Shape{
public Triangle(int x,int y){
super(x,y);
}
public void draw(){
//Draw Triangle using x and y : base * height /2
System.out.println("draw Triangle with area:"+ (x * y) / 2);
}
}
class Circle extends Shape{
public Circle(int x,int y){
super(x,y);
}
public void draw(){
//Draw Circle using x as radius ( PI * radius * radius
System.out.println("draw Circle with area:"+ ( 3.14 * x * x ));
}
}
public class AbstractBaseClass{
public static void main(String args[]){
Shape s = new Rectangle(5,10);
s.draw();
s = new Circle(5,10);
s.draw();
s = new Triangle(5,10);
s.draw();
}
}
输出:
draw Rectangle with area:50
draw Circle with area:78.5
draw Triangle with area:25
上面的代码涵盖了第1点和第2点。如果基类有一些实现并调用子类方法来完成draw()函数,则可以将draw()方法更改为模板方法。
现在使用Template方法模式的相同示例:
abstract class Shape{
int x;
int y;
public Shape(int x,int y){
this.x = x;
this.y = y;
}
public abstract void draw();
// drawShape is template method
public void drawShape(){
System.out.println("Drawing shape from Base class begins");
draw();
System.out.println("Drawing shape from Base class ends");
}
}
class Rectangle extends Shape{
public Rectangle(int x,int y){
super(x,y);
}
public void draw(){
//Draw Rectangle using x and y : length * width
System.out.println("draw Rectangle with area:"+ (x * y));
}
}
class Triangle extends Shape{
public Triangle(int x,int y){
super(x,y);
}
public void draw(){
//Draw Triangle using x and y : base * height /2
System.out.println("draw Triangle with area:"+ (x * y) / 2);
}
}
class Circle extends Shape{
public Circle(int x,int y){
super(x,y);
}
public void draw(){
//Draw Circle using x as radius ( PI * radius * radius
System.out.println("draw Circle with area:"+ ( 3.14 * x * x ));
}
}
public class AbstractBaseClass{
public static void main(String args[]){
Shape s = new Rectangle(5,10);
s.drawShape();
s = new Circle(5,10);
s.drawShape();
s = new Triangle(5,10);
s.drawShape();
}
}
输出:
Drawing shape from Base class begins
draw Rectangle with area:50
Drawing shape from Base class ends
Drawing shape from Base class begins
draw Circle with area:78.5
Drawing shape from Base class ends
Drawing shape from Base class begins
draw Triangle with area:25
Drawing shape from Base class ends
一旦确定必须将方法作为方法abstract ,您有两个选择:用户interface或abstract类。 您可以在interface声明方法,并将abstract类定义为实现interface类。