问题描述:

I have an abstract class A with 1 method called public int get(int x, int y).

Classes B,C,D have 1 method which are all same and they extends to the abstract class A.

In a class Car, the Car constructor receives String argument type that should be used to decide which one of B, C, D have to be used in the class.

Apparently, I am using if...else conditional statements based on the type to do it.

So the codes look like

if(type.equals("B")){

A = new B();

} else if(type.equals("C")){

A = new C();

} //and so on..

Is there any elegant way that I can use string argument just as it is to decide which one of 3 classes to use?

网友答案:

You could use the interface / abstract class as an argument in the constructor instead of using a String.

public Car(A a) { this.a = a; }

And then elsewhere:

B b = new B();
new Car(b);

This is called dependency injection.

网友答案:

You can use Class.forName(String) to get a Class object and then instantiate it using newInstance()

相关阅读:
Top