View RSS Feed

Advanced Java

Generic Classes in Java

Rate this Entry
by , 02-18-2012 at 03:52 PM (848 Views)
Your Java classes could also be generified. Generics are not restricted or bound to any pre-defined classes of Java. This is also applicable to customized written classes of Java.

Simple generic class is explained here by this code.
Java Code: This is the code to explain generic class
public class GenericTestFactory<E> {
    Class myClass = null;
    public GenericTestFactory(Class myClass) {
        this.myClass = myClass;
    }
    public E createInstance()
    throws IllegalAccessException, InstantiationException {
        return (E) this.myClass.newInstance();
    }
}
The <E> is considered to be a type token.This shows that class might have a type set, when instantiated. Example is as following:

Java Code: This is the code to expalin generic type casting
GenericTestFactory<MyClass> factory =
    new GenericTestFactory<MyClass>(MyClass.class);
MyClass myClassInstance = factory.createInstance();
Every GenerticTestFactory instance might get generified into varying types. Two examples are present here.

Java Code: This is the code to explain the generified
GenericTestFactory<MyClass> factory =
    new GenericTestFactory<MyClass>(MyClass.class);
MyClass myClassInstance = factory.createInstance();
GenericTestFactory<SomeObject> factory =
    new GenericTestFactory<SomeObject>(SomeObject.class);
SomeObject someObjectInstance = factory.createInstance();

Submit "Generic Classes in Java" to Facebook Submit "Generic Classes in Java" to Digg Submit "Generic Classes in Java" to del.icio.us Submit "Generic Classes in Java" to StumbleUpon Submit "Generic Classes in Java" to Google

Categories
Generics

Comments