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?
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
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)
?
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