Tuesday, April 1, 2014

Generic types in java - basic concept


I am trying to understand the concept of Generics in java. In the introduction to Generic Types, this example is given:



Java Code:



public class Box {
private Object object;

public void set(Object object) { this.object = object; }
public Object get() { return object; }
}

"Since Since its methods accept or return an Object, you are free to pass in whatever you want, provided that it is not one of the primitive types." - I understand this.

But then it has been changed to a generic class:



Java Code:



/**
* Generic version of the Box class.
* @param <T> the type of the value being boxed
*/
public class Box<T> {
// T stands for "Type"
private T t;

public void set(T t) { this.t = t; }
public T get() { return t; }
}

"As you can see, all occurrences of Object are replaced by T. A type variable can be any non-primitive type you specify: any class type, any interface type, any array type, or even another type variable."

We can use any type in place of an Object, because Object is a superclass of all classes. But T (or any other class) is not a superclass of all classes. So how do we justify any class being used in place of a random T or any other class?


Thank you in advance.



No comments:

Post a Comment