Defining your own Generic Class

Apart from using Generics with classes in the Java framework, we can create our own generic classes.

Lets create a generic class named MyGenericClass as follows :

public class MyGenericClass<T> {
    T obj;
    MyGenericClass(T o) {
        obj = o;    }

    T getObj() {
        return obj;    }

    public void show() {
        System.out.println("The type of obj is : " + obj.getClass().getName());    }
}

Here whatever the object we receive in the constructor and the value of T used while declaring the object tells what type  is going to be used.

Lets use this class in our test class to see its usage :

MyGenericClass<String> myG1 = new MyGenericClass<String>("Sandeep");System.out.println(myG1.getObj());myG1.show();

MyGenericClass<Integer> myG2 = new MyGenericClass<Integer>(100);System.out.println(myG2.getObj());myG2.show();

The above declarations change the value of T to java.lang.String and java.lang.Integer at runtime and produce the output accordingly.

Try this variation :

List<String> strList = new ArrayList<String>();strList.add("Sandeep");strList.add("Ravi");
MyGenericClass<List<String>> myG3 = new MyGenericClass<ArrayList<String>>(strList);System.out.println(myG1.getObj());myG1.show();

The above code doesnt compile as the type-parameter is not the same while creating the object.
The reference type of the parent can be used to create child object, but the type-parameter needs to be the same. So in this case, if MyGenericClass had a parent class, we could have used that; but we need to use either List or ArrayList on both sides of the declaration.

The code for the above example can be found here.

Comments

Popular posts from this blog

Collection Framework - HashSet And LinkedHashSet class

Collection Framework - Cursors in Java

Hashed data structures