4) Generics

Intro

Generic Class

Generic Method

Generic Class inheritance

Generic Interface

Introduction :

Generics in Java is similar to templates in C++. The idea is to allow type (Integer, String, … etc and user defined types) to be a parameter to methods, classes and interfaces. For example, classes like HashSet, ArrayList, HashMap, etc use generics very well. We can use them for any type.

Code :

package com.gns.generics;

class Parcel {
	private Object obj;

	public Object getObj() {
		return obj;
	}

	public void setObj(Object obj) {
		this.obj = obj;
	}
}

class Phone {

}

class Book {

}

public class Generic1 {
	public static void main(String[] args) {
		Parcel parcel = new Parcel();
		parcel.setObj(new Book());
		System.out.println((Phone) parcel.getObj());
	}
}

As shown in the preceding code, the declaration of generic class Parcel includes the type parameter T. After adding the type information, it’s read as Parcel or Parcel of T. The generic class Parcel defines a private instance variable of type T, and get() and set() methods to retrieve and set its value. Methods get() and set() use the parameter type T as their method parameter and return type.

The first occurrence of T is different from its remaining occur- rences because only the first one is surrounded by <>.

With the generic class Parcel, UseGenericParcel can use method set() to assign an object of type Book. But UseGenericParcel can’t cast the retrieved object to an unrelated class, say, Phone. If it tries to do so, the code won’t compile (as shown in figure).

Code :

package com.gns.generics;

class Parcel<T> {
	private T obj;

	public T getObj() {
		return obj;
	}

	public void setObj(T obj) {
		this.obj = obj;
	}
}

class Phone {

}

class Book {

}

public class Generic2 {
	public static void main(String[] args) {
		Parcel<Book> parcel = new Parcel<Book>();
		parcel.setObj(new Book());
		System.out.println((Phone) parcel.getObj());
	}
}

Last updated