Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the point of T extends SomeClass?

Tags:

What is the difference with a method declaration like this:

public <T extends SomeClass> void doSomething(T obj) {     // Do something. } 

And this:

public void doSomething(SomeClass obj) {     // Do Something. } 

The way I see it, both of them are specifying that the object passed in must be a subclass of type SomeClass, so why bother with the generics at all in this instance?

like image 638
christopher Avatar asked Dec 18 '13 15:12

christopher


People also ask

What is difference between extends and super in generics?

extends Number> represents a list of Number or its sub-types such as Integer and Double. Lower Bounded Wildcards: List<? super Integer> represents a list of Integer or its super-types Number and Object.

What is a bounded type parameter?

There may be times when you want to restrict the types that can be used as type arguments in a parameterized type. For example, a method that operates on numbers might only want to accept instances of Number or its subclasses. This is what bounded type parameters are for.

What are formal type parameters in java?

formal parameter — the identifier used in a method to stand for the value that is passed into the method by a caller. actual parameter — the actual value that is passed into the method by a caller. For example, the 200 used when processDeposit is called is an actual parameter.

What are generics in Java?

Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different data types.


1 Answers

In your case it doesn't make much difference.

But consider the following:

public <T extends SomeClass> void doSomething(List<T> obj) 

In this case you could call the method the following ways:

obj.doSomething(new ArrayList<SubclassOfSomeClass>()); obj.doSomething(new ArrayList<SomeClass>()); 

If you would use

public void doSomething(List<SomeClass> obj) 

You would only be able to do this:

obj.doSomething(new ArrayList<SomeClass>()); 
like image 157
micha Avatar answered Oct 04 '22 05:10

micha