I'm trying to understand generic methods in Java. Given the following code:
public class GenericTest {
interface Shape {
public long area();
}
public static class Triangle implements Shape
{
private long base, height;
public long area() { return (base * height) / 2; }
}
public static class Rectangle implements Shape
{
private long width, height;
public long area() { return width * height; }
}
public <T extends Shape> long area1(T shape)
{
return shape.area();
}
public long area2(Shape shape)
{
return shape.area();
}
}
I can't see/understand why I should use/implement area1 instead of area2 (or vice versa). Am I missing something? Don't both methods do the same thing?
It has left me a bit confused regarding generics in Java
extends typeportion was not necessary -- which resulted in a great deal of confusion, prompting my previous question: link And seeing that the problem could be resolved without generics at all, I posted this question to determine why I would ever want to use them if I always had to know the type (unlike a C++ template).The answer given by @LukasKnuth that filled in the missing piece of the puzzle