我正在学习如何使用工厂模式在 Java 中创建对象。我想创建类来管理汽车。汽车可以是小型的,也可以是大型的。我创建了一个接口(interface),它定义了要由实现类实现的方法。抽象类实现小型和大型汽车共享的接口(interface)的一些通用方法。具体的 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 接口(interface)上定义的所有其他方法,但无法访问抽象类上定义但接口(interface)上未定义的 isTankFull()
方法。我希望我的解释足够清楚。
最佳答案
您看不到该方法的原因是您的 c
对象被声明为 Car
接口(interface)。当然,当它从你的工厂方法中出来时,它是一个 SmallCar
,但你的变量只是接口(interface)。您可以将声明更改为 AbstractCar c = CarFactory.createCar("SmallCar", regnum);
。
在使用接口(interface)时实现此目的的另一种方法是在尝试访问不在接口(interface)上的方法时将 c
对象强制转换为 AbstractCar
,但是您需要小心,因为您的工厂始终有可能返回实现 Car
的对象,但不是 AbstractCar
。
if (c instanceof AbstractCar) {
((AbstarctCar)c).isTankFull();
}
当然,另一个简单的解决方案是将方法添加到接口(interface)中,尽管这会消除这个问题的教学机会。
关于java - 接口(interface)、抽象类和抽象类的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28944064/