英文:
Java instantiating a generic type which implements an interface
问题
我在学习Java中的面向对象编程(OOP)概念和内部类时有一个问题。
假设有一个名为CarFactory的类,它有一个buildCar()方法,返回一个Car。这个工厂会构建几个实现了Car接口的Models。
因此,我创建了一个Car接口,然后Models实现了Car接口。
如何返回一个是接口Car的Car对象?
我知道我可以实例化一个实现了Car接口的Model,但我想创建一个通用的方法,返回任何实现了Car接口的Model。
CarFactory.java
public class CarFactory {
Car buildCar() {
return new Car(); // ??? 我不能这样做
}
}
Car.java
public interface Car {
abstract class Construct {
abstract void constructCar();
}
void turn();
void stop();
void accelerate();
// ...
}
ModelExample.java
public class ModelExample implements Car {
static CarFactory factory;
public ModelExample() {
this.factory = new CarFactory();
}
class Construct extends Car.Construct {
void constructCar() {
System.out.println("Model Example constructed");
}
}
}
英文:
I got a question while studying OOP concept and inner classes in Java.
Let's say there is a class CarFactory, and it has buildCar() method that returns a Car. This factory builds several Models that implement a Car.
Therefore, I made a Car interface and the Models implement Car.
How can you return a Car that is an interface?
I know that I can instantiate a Model that implements a Car, but I want to make a general method that returns any Model that implements a Car.
CarFactory.java
public class CarFactory {
Car buildCar() {
return new Car(); // ??? I cannot do this
}
}
Car.java
public interface Car {
abstract class Construct {
abstract void constructCar();
}
void turn();
void stop();
void accelerate();
...
}
ModelExample.java
public class ModelExample implements Car {
static CarFactory factory;
public ModelExample() {
this.factory = new CarFactory();
}
class Construct extends Car.Construct {
void constructCar() {
System.out.println("Model Example constructed");
}
}
}
答案1
得分: 0
在Java中,您不能初始化接口。我建议您学习抽象工厂设计模式。
针对您的情况,您需要一个名为AbstractCarFactory的接口,其中包含一个名为buildCar的方法。然后,您可以为每种类型的汽车创建AbstractCarFactory的子类。
英文:
In Java, you cannot initialize interfaces. I suggest you study the Abstract Factory design pattern.
For your case, you would need an interface AbstractCarFactory, which contains a method Car buildCar. You can then create subclasses of the AbstractCarFactory for each type of car.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论