Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
141 views
in Technique[技术] by (71.8m points)

java - What type parameters would an innerclass and interface have in the following situation?

Suppose we have a generic class that implements a generic interface like this

GenericClass.java

public class GenericClass<T> implements GenericInterface<T> {

    private class AnotherClass<T> {
        T aVariable;
    }

    @Override
    public T aMethod() {
        return null;
    }
}

GenericInterface.java

public interface GenericInterface<T> {
    T aMethod();
}

What would be the type parameter passed on in the interface? Also, what would be the type parameter passed to the nested class inside GenericClass.

question from:https://stackoverflow.com/questions/65872074/what-type-parameters-would-an-innerclass-and-interface-have-in-the-following-sit

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'll take your comment as the actual question:

If I create a new instance of GenericClass like this: new GenericClass then will the interface it implements also be GenericInterface and will the inner class als be AnotherClass

Yes, it's gonna be GenericInterface<Integer>. No, it's not gonna be AnotherClass<Integer>.

class GenericClass<T> introduces a type-parameter T that can be used e.g. with a generic interface like you do. Now be careful: class AnotherClass<T> that is nested within GenericClass introduces another type-parameter T that hides the one that GenericClass has introduced.

If you want AnotherClass to use T of GenericClass, then simply skip the <T> for AnotherClass.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...