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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With