java - 将接口(interface)作为构造函数传递给类

标签 java interface

这是我的代码:

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/

相关文章:

c++ - 如何从父类转换为子类的接口(interface)

java - 改造自定义回调通用类型

java - 从 URL 检索 HTML 标签和纯文本

java - 我的应用程序的用户界面存在多个问题

java - 有没有办法在子类上实现一个方法,我可以从它的子类访问属性?

user-interface - 用于批处理文件的 GUI?

java - 在 Java 接口(interface)中,我如何*不*使用从父接口(interface)继承的特定方法?

java - 带有变量的Android TextView id?

java - 通用观察者 - 类型转换问题

java - 我怎样才能将一个整数分解成单个数字?