Java实例化实现了接口的泛型类型

huangapple go评论62阅读模式
英文:

Java instantiating a generic type which implements an interface

问题

我在学习Java中的面向对象编程(OOP)概念和内部类时有一个问题。

假设有一个名为CarFactory的类,它有一个buildCar()方法,返回一个Car。这个工厂会构建几个实现了Car接口的Models

因此,我创建了一个Car接口,然后Models实现了Car接口。

如何返回一个是接口CarCar对象?

我知道我可以实例化一个实现了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.

huangapple
  • 本文由 发表于 2020年4月9日 10:32:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/61113046.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定