Generic Class Hierarchies in Java
Generic means parameterized types introduced in java5. These help in creating classes, interfaces, methods, etc. A class or method which works on parameterized type known as “generic class ” or “generic method”. Generics is a combination of language properties of the definition and use of Generic types and methods. Collections were used before Generics which holds any type of objects i.e. non-generic. Using Generics, it has become possible to create a single class, interface, or method that automatically works with all types of data(Integer, String, Float, etc). It has expanded the ability to reuse the code safely and easily. Generics also provide type safety (ensuring that an operation is being performed on the right type of data before executing that operation).
Hierarchical classifications are allowed by Inheritance. Superclass is a class that is inherited. The subclass is a class that does inherit. It inherits all members defined by super-class and adds its own, unique elements. These uses extends as a keyword to do so.
Sometimes generic class acts like super-class or subclass. In Generic Hierarchy, All sub-classes move up any of the parameter types that are essential by super-class of generic in the hierarchy. This is the same as constructor parameters being moved up in a hierarchy.
Example 1: Generic super-class
Java
import java.io.*;
class Generic1<T> {
T obj;
Generic1(T o1) { obj = o1; }
T getobj1() { return obj; }
}
class Generic2<T, V> extends Generic1<T> {
V obj2;
Generic2(T o1, V o2)
{
super (o1);
obj2 = o2;
}
V getobj2() { return obj2; }
}
class GFG {
public static void main(String[] args)
{
Generic2<String, Integer> x
= new Generic2<String, Integer>( "value : " ,
100 );
System.out.println(x.getobj1());
System.out.println(x.getobj2());
}
}
|
Note: A subclass can freely add its own type parameters, if necessary.
Example 2: Non-generic sub-class of generic sub-class
Java
import java.io.*;
class NonGen {
int n;
NonGen( int i) { n = i; }
int getval() { return n; }
}
class Gen<T> extends NonGen {
T obj;
Gen(T o1, int i)
{
super (i);
obj = o1;
}
T getobj() { return obj; }
}
class GFG {
public static void main(String[] args)
{
Gen<String> w = new Gen<String>( "Hello" , 2021 );
System.out.println(w.getobj() + " " + w.getval());
}
}
|
Last Updated :
17 May, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...