Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

type T parameters in generic method arguments

Tags:

java

generics

Suppose the following classes are defined:

class Shape { }
class Circle extends Shape {  }
class Rectangle extends Shape { }  //  1

You can write a generic method to draw different shapes:

public static <T extends Shape> void draw(T shape) { }   // 2

The Java compiler replaces T with Shape:

public static void draw(Shape shape) {  } // 3

My Question is, if we define directly // 3 in our class then we still be able to pass Shape, Circle and Rectangle reference to method at //3. Then why do we need to write // 2 generic method with type parameter <T extends Shape> which is untimately going to be same as //3 ?

You can refer this link with same example : http://docs.oracle.com/javase/tutorial/java/generics/genMethods.html

like image 319
AmitG Avatar asked Mar 21 '13 14:03

AmitG


2 Answers

You may or may not need it. You need it if your method has to deal with other objects of the type T that must match the type of T extends Shape exactly, for example:

public static <T extends Shape> void drawWithShadow(T shape, Class<T> shapeClass) {
    // The shadow must be the same shape as what's passed in
    T shadow = shapeClass.newInstance();
    // Set the shadow's properties to from the shape...
    shadow.draw(); // First, draw the shadow
    shape.draw();  // Now draw the shape on top of it
}

Above, passing Shape would not be enough, because we wouldn't be able to make the shadow of the exactly same type.

In case when there is no such requirement, a simple Shape would be sufficient.

like image 107
Sergey Kalinichenko Avatar answered Oct 19 '22 00:10

Sergey Kalinichenko


In this particular case, you don't need a generic method.

But you can do more in a generic method than call a dynamically linked method on its arguments.

For example, you might have a generic method that accepts and returns a collection of T elements. Parameterizing it by type allows you to use it on multiple collection types.

Other examples where generic methods are useful are in this Java tutorial.

like image 34
Andy Thomas Avatar answered Oct 19 '22 00:10

Andy Thomas