type T parameters in generic method arguments

generics, java

Solution

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.

Problem

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

Original source