【发布时间】:2015-03-09 14:10:32
【问题描述】:
我正在学习如何使用 工厂模式 在 Java 中创建对象。我想创建类来管理汽车。一辆车可以很小也可以很大。我创建了一个接口,它定义了实现类要实现的方法。抽象类实现了小型和大型汽车共享的接口的一些常用方法。具体的 SmallCar 和 LargeCar 类实现了抽象类的其余方法。
汽车界面
public interface Car {
String getRegistrationNumber();
void drive();
}
抽象汽车类实现汽车界面
public abstract class AbstractCar implements Car {
private final RegistrationNumber regNumber;
private boolean tankFull = true;
public AbstractCar(RegistrationNumber regNumber) {
this.regNumber = regNumber;
}
@Override
public final String getregistrationNumber() {
return regNumber.toString();
}
/**This method is not defined in the implemented Car interface. I added it to
*the abstract class because I want subclasses of these abstract class
*to have this method*/
public boolean isTankFull() {
return tankFull;
}
}
小型车扩展抽象类
public final class SmallCar extends AbstractCar {
public SmallCar(RegistrationNumber regNum) {
super(regNum);
}
@Override
public void drive() {
//implemented here
}
}
工厂类:
该类负责创建特定类型汽车的实例。
public final class CarFactory {
public static Car createCar(String carType, RegistrationNumber regNum) {
Car car = null;
if (carType.equals("Small") {
car = new SmallCar(regNum);
}
return car;
}
主要方法
RegistrationNumber regNum = new RegistrationNumber('a', 1234);
Car c = CarFactory.createCar("Small", regNum);
c.getRegistrationNumber(); //this works
c.isTankFull(); //this instance of Car cannot access the isTankFull method defined on the abstract class. The method is not defined on the Car interface though. I do not understand why.
挑战在于 Car 的实例可以访问定义在 Car 接口上的所有其他方法,但它不能访问定义在抽象类上但未在接口上定义的 isTankFull() 方法。我希望我的解释足够清楚。
【问题讨论】:
-
这里没什么奇怪的。将isTankFull放在界面上。
-
您需要将您的实例转换为 AbstractCar
标签: java oop interface abstract-class late-binding