Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the point of making a class generic?

when you have a method, I understand that it makes sense to declare it generic so that i can take generic arguments. Like this:

public <T> void function(T element) {
    // Some code...
}

But what exactly is the idea behind making a whole class generic if I can simply declare every method generic?

like image 303
user1420042 Avatar asked Feb 22 '13 11:02

user1420042


2 Answers

Well, the difference is if you try to make each method in your class generic the generic type you'd use in your say firstGenericMethod may or may not be the same type.What i mean is.

public <T> void firstGenMethod(...){

}

public <T> void secondGenMethod(...){

}

Test:

  SomeClass ref = new SomeClass();
  ref.firstGenMethod("string");
  ref.secondGenMethod(123);//legal as this generic type is not related to the generic type which is used by firstGenMethod

In the above case there is no gaurentee that both the methods have the same generic type.It depends on how you invoke them. If you make the class generic though, the type is applied to all the methods inside that class.

class Test<T>{

    public void firstGenMethod(T t){

    }

    public  void secondGenMethod(T t){

    }
}

Test:

 Test<String> testingString = new Test<>();
   testingString.firstGenMethod("abc");
   testingString.firstGenMethod(123);// invalid as your Test class only expects String in this case

You'd usually make your class generic where you'd want the entire behaviour(methods) of that class to process on the same type. best examples are class's in Java Collection Framework

like image 173
PermGenError Avatar answered Oct 23 '22 06:10

PermGenError


Have a look at the Collection classes. Take List<T> as an example. If the class weren't declared generic, how would you make sure that only elements of the correct class could be inserted into the list? And how would you know what you get when calling ArrayList.get(i)?

like image 39
Axel Avatar answered Oct 23 '22 04:10

Axel