- It helps us to separate logic from data type, means no matter what type of data type we are passing to method, will be handled using the same function.
- In other way, we can avoid polymorphism, means only one function can handle different data type rather than defining many function with different kind of data type.
- Generic type invocation as being similar to an ordinary method invocation, but instead of passing an argument to a method, you're passing a type argument
to use this we need to define the class data type at time of creating the object, here is an example for that suppose we have a class defince as follows :
public class Box<T> {
// T stands for "Type"
private T t;
public void add(T t) {
this.t = t;
}
public T get() {
return t;
}
}
So while creating the object of the Box class we do as follows:
Box<Integer> integerBox = new Box<Integer>();// which means the invoking is always knowns as parameterized type, means whenever we create and object we also pass the data type,
Check out these videos for more understanding :
Generic in c#
Generic in Java :
No comments:
Post a Comment