in Java syntax, Class<? extends Something>

前端 未结 5 1341
遇见更好的自我
遇见更好的自我 2020-12-12 16:57

Class

Here\'s my interpretation, it\'s class template but the class ? means the name of the class is undetermined and it exte

相关标签:
5条回答
  • 2020-12-12 17:33

    You're right

    Definition is that the class has to be subtype of Something

    It's the same as Class<T>, but there is a condition that T must extends Something Or implements Something as Anthony Accioly suggested

    It can also be class Something itself

    0 讨论(0)
  • 2020-12-12 17:38

    There are a few confusing answers here so I will try and clear this up. You define a generic as such:

    public class Foo<T> {
        private T t;
        public void setValue(T t) {
            this.t = t;
        }
        public T getValue() {
            return t;
        }
    }
    

    If you want a generic on Foo to always extend a class Bar you would declare it as such:

    public class Foo<T extends Bar> {
        private T t;
        public void setValue(T t) {
            this.t = t;
        }
        public T getValue() {
            return t;
        }
    }
    

    The ? is used when you declare a variable.

    Foo<? extends Bar>foo = getFoo();
    

    OR

    DoSomething(List<? extends Bar> listOfBarObjects) {
        //internals
    }
    
    0 讨论(0)
  • 2020-12-12 17:45

    You're correct.

    In Java generics, the ? operator means "any class". The extends keyword may be used to qualify that to "any class which extends/implements Something (or is Something).

    Thus you have "the Class of some class, but that class must be or extend/implement Something".

    0 讨论(0)
  • 2020-12-12 17:51

    You're correct.

    However usually you will want to name the class that extends Something and write e.g. <E extends Something>. If you use ? you can't do anything with the given type later.

    0 讨论(0)
  • 2020-12-12 17:52

    You are almost right. Basically, Java has no concept of templates (C++ has). This is called generics. And this defines a generic class Class<> with the generics' attribute being any subclass of Something.

    I suggest reading up "What are the differences between “generic” types in C++ and Java?" if you want to get the difference between templates and generics.

    0 讨论(0)
提交回复
热议问题