这是我的代码:
public interface Baseinterface {}
abstract class Interface1 implements Baseinterface{}
abstract class Interface2 implements Baseinterface{}
public interface Classinterface {}
我想使用这段代码:
public class Myclass(Baseinterface interfaceversion) implements Classinterface{}
接口(interface)实现的类型作为构造函数传递。 因此,当在这两个抽象类中定义一个函数时,我的实际类知道要使用哪一个。我对java相当陌生。 谢谢。
最佳答案
我可能误解了问题的本质,但这里是:
给出的代码描述了两个实现与接口(interface)定义的相同方法的抽象类:
interface BaseInterface {
void foo();
}
abstract class ITestA implements BaseInterface {
public void foo() {
System.out.print("A");
}
}
abstract class ITestB implements BaseInterface {
public void foo() {
System.out.print("B");
}
}
public class MyClass {
private BaseInterface enclosed;
MyClass(BaseInterface base) {
enclosed = base;
}
public void foo() {
enclosed.foo(); // call the implementation specific to the instance passed in by constructor
}
}
这可以这样称呼:
public class Test {
void bar() {
// This may look weird cause we're defining an anonymous implementation of the abstract class, without adding any new implementation details
ITestA impl = new ITestA() {};
MyClass myClass = new MyClass(impl);
myClass.foo(); // prints "A"
}
}
关于java - 将接口(interface)作为构造函数传递给类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47060079/