0

I am reading a Java text book and the writer to show usefulness of generic types in methods use an example:

public class BoundedTypeDemo {
    public static void main(String[] args ) {
        Rectangle rectangle = new Rectangle(2, 2);
        Circle circle = new Circle(2);
        System.out.println("Same area? " +
        equalArea(rectangle, circle));
    }

    public static <E extends GeometricObject> boolean equalArea(E object1, E object2) {
        return object1.getArea() == object2.getArea();
    }
 }

This is a ridiculous example... I do not understand where is the usefulness of using generic type in this particular example cause we could use GeometricObject as the type of equalArea method's parameters

  • 1
    It's not a good example, no. :-) (Not without some context of where and why it's being used in the book.) But what's your actual question? "Is it a good example?" "What would be a better example?" "Why have generics?" – T.J. Crowder Feb 07 '20 at 12:44
  • 1
    yes, you're right, this is not a good example. if think it is even a bad one, because using generics introduces unecessary complexity to the code, when they are not necessarily needed. – Willi Mentzel Feb 07 '20 at 12:44
  • Someone didn't want to write `GeometricObject` twice, possibly. – M. Prokhorov Feb 07 '20 at 12:45
  • ` boolean equalAreas(List list1, List list2)` (that compares the areas of the corresponding list elements) would be a better example. – Andy Turner Feb 07 '20 at 12:51
  • @M.Prokhorov then they should have called it `Shape` ;) – Andy Turner Feb 07 '20 at 12:51

0 Answers0