Domanda

I started studying Java-generics. And I have some misunderstanding of the generics syntax and its meaning. I beg to treat with understanding if my question seems too trivial.

  1. You can write:

    public class MyClass<SomeClass> {}
    
  2. and you can write:

    public class MyClass<C extends SomeClass> {} 
    
  3. and you can write also:

    public class MyClass<? extends SomeClass> {} 
    

What is the difference between these cases?

  1. The first case is absolutely clear to me: you can use instance of SomeClass and instance of his subclasses as class's parameter for MyClass.
  2. I think that in this case you can only use instance of MyClass's subclasses
  3. The same: only use instance of MyClass's subclasses as class's parameter for MyClass.

Are my guesses right or not? And especially what is the difference between the using of the second and third cases?

Thanks in advance for explanation!

È stato utile?

Soluzione

Well the difference is you cant use ? in generic class declaration

public class MyClass<? extends SomeClass> {} // this isn't valid  

The above declaration leads to compiler error.

From Documentation:

A generic class is defined with the following format:

class name { /* ... */ } The type parameter section, delimited by angle brackets (<>), follows the class name. It specifies the type parameters (also called type variables) T1, T2, ..., and Tn.

public class MyClass<C extends SomeClass> {} 

In this declaration C is a type-argument which could be of type SomeClass or any of its SubClass's.

Example :

Class SomeOtherClass extends SomeClass {
}

MyClass clazz = new MyClass<SomeOtherClass>();
MyClass clazz = new MyClass<SomeClass>(); 
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top