在接口中实现方法

时间:2014-02-20 15:42:14

标签: java generics java-7

我有像

这样的实现
private List<E> myList = new ArrayList<E>();//just a local variable of MyClass

public MyClass<E> methodFromInterface(Interface<E> Obj) {
    MyClass<E> ooo = (MyClass<E>) obj;
}

我面临的主要问题是我在MyClass中有一些变量,虽然我是对MyClass进行类型转换的接口,但我无法访问这些变量。 我在哪里错了?

1 个答案:

答案 0 :(得分:1)

假设您的界面如下所示:

public interface MyInterface<E> {
    MyClass<E> methodFromInterface(Interface<E> Obj);
}

然后你可以编写这样的代码来访问myList变量:

public MyClass<E> implements MyInterface<E> {

    private List<E> myList = new ArrayList<E>();

    public MyClass<E> methodFromInterface(MyInterface<E> obj) {
        MyClass<E> ooo = (MyClass<E>) obj;

        // now you can access 2 different instances of `myList`
        List<E> firstInstance = this.myList; 
        List<E> secondInstance = ooo.myList;
        // note that these will not be the same instance of a List!
    }
}

免责声明:我必须补充说,这对你的课来说似乎是一个非常糟糕的结构。我有一个interface定义了一个方法,它接受一个自身的实例并返回一个子类型,这似乎很奇怪。我想你可能需要更多地了解继承,接口,超类型等。

相关问题