Friday, July 1, 2011

Writing Generic interface

A class or an interface is generic if it has one or more type variable. Type variable are delimited by angle brackets and follow the class (or the interface) name:

public interface List<T> extends Collection<T> {
  ...
}

Roughly speaking, type variables act as parameters and provide the information the compiler needs to make its checks.

Many classes in the Java library, such as the entire Collections Framework, were modified to be generic. The List interface we've used in the first code snippet, for example, is now a generic class. In that snippet, box was a reference to a List<Apple> object, an instance of a class implementing the List interface with one type variable: Apple. The type variable is the parameter that the compiler uses when automatically casting the result of the get method to an Apple reference.

In fact, the new generic signature or the get method of the interface List is:

T get(int index);

The method get returns indeed an object of type T, where T is the type variable specified in the List<T> declaration.

No comments:

Post a Comment

Chitika