Monday, March 9, 2009

Generic Types  


Generic Types:                 

    Just we update our Box class to use generics. We'll first create a generic type declaration by changing the code "public class Box" to "public class Box"; this introduces one type variable, named T, that can be used anywhere inside the class. This same technique can be applied to interfaces as well. There's nothing particularly complex about this concept. In fact, it's quite similar to what you already know about variables in general. Just think of T as a special kind of variable, whose "value" will be whatever type you pass in; this can be any class type, any interface type, or even another type variable. It just can't be any of the primitive data types. In this context, we also say that T is a formal type parameter of the Box class. 

 * Generic version of the Box class. 
public class Box {

  private T t; // T stands for "Type"  

  public void add(T t) {
  this.t = t;

  public T get() {
  return t;

As you can see, we've replaced all occurrences of Object with T. To reference this generic class from within your own code, you must perform a generic type invocation, which replaces T with some concrete value, such as Integer:

What next?

You can also bookmark this post using your favorite bookmarking service:

Related Posts by Categories

0 comments: to “ Generic Types

Extension Factory Builder