The term generic means parameterized type. It enables us to create classes, interfaces and methods in which the type of data upon which they operates is specified as a parameter. Using generics, we can create a single class that works on different types of data. A class, interface or method that operates on a parameterized type is called generic, as in generic class or in generic method.
It is also important to know that Java has always given us the ability to create generalized classes, interfaces and methods by using through the references of type Object. Object is the superclass of all other classes, an Object reference can refer to any type object.
Thus in pre-generic code a generalized class,interface and method can be created but without type safety. But generics solved this problem which was lacking previously.
As previously generalized classes, interfaces and methods were created but without type safety which means we have to explicitly cast to translate between Object and the type of data that is being operated upon. whereas all casts are automatically done in generic with type safety.
Here is a simple example which demonstrate how to use a generic class ....
class Gen<T> {
T obj;
Gen(T o) {
obj = o;
}
T getObj() {
return obj;
}
}
class GenDemo {
public static void main(String[] arg) {
Gen<Integer> iobj = new Gen<Integer>(10);
int x = iobj.getObj();
System.out.println("Integer = "+x);
Gen<Double> iobj = new Gen<Double>(10.20);
int y = iobj.getObj();
System.out.println("Double = "+y);
}
}
Output:
Integer = 10
Double = 10.20
It is also important to know that Java has always given us the ability to create generalized classes, interfaces and methods by using through the references of type Object. Object is the superclass of all other classes, an Object reference can refer to any type object.
Thus in pre-generic code a generalized class,interface and method can be created but without type safety. But generics solved this problem which was lacking previously.
As previously generalized classes, interfaces and methods were created but without type safety which means we have to explicitly cast to translate between Object and the type of data that is being operated upon. whereas all casts are automatically done in generic with type safety.
Here is a simple example which demonstrate how to use a generic class ....
class Gen<T> {
T obj;
Gen(T o) {
obj = o;
}
T getObj() {
return obj;
}
}
class GenDemo {
public static void main(String[] arg) {
Gen<Integer> iobj = new Gen<Integer>(10);
int x = iobj.getObj();
System.out.println("Integer = "+x);
Gen<Double> iobj = new Gen<Double>(10.20);
int y = iobj.getObj();
System.out.println("Double = "+y);
}
}
Output:
Integer = 10
Double = 10.20
No comments:
Post a Comment