Formal definition of generics in java :
abstract class Container<T> {
T content;// can be sugar , wood, coal and so on…
public void setContent(T value){
content = value;
}
public T getContent(){
return content;
}
//we can handle calculation of quantities as follows.
// create an abstract method for any custom calculation
protected abstract int calculateQuantity();
// provide a default implementation
public int calculateDefaultQuantity(){
//some logic
}
}
3. TYPE SAFETY :
Generics are very helpful in ensuring type safety in java code
consider following class which validates Views :
class Validator<T extends View>{
public validate(T view){
//validation code
}
}
Above BOUNDED PARAMETER ‘T’ ensures that only the classes
which are Views are allowed to be operated by this class.