Monday, March 9, 2009

generics introduction  

0 comments

Generics:                   

   Generics add stability to your code by making more of your bugs detectable at compile time. Some programmers choose to learn generics by studying the Java Collections Framework; after all, generics are heavily used by those classes. However, since we haven't yet covered collections, this chapter will focus primarily on simple "collections-like" examples that we'll design from scratch. This hands-on approach will teach you the necessary syntax and terminology while demonstrating the various kinds of problems that generics were designed to solve. 

A Simple Class

                       Box class need only provide two methods: add, which adds an object to the box, and get, which retrieves it:

 public class Box {

  private Object object;

  public void add(Object object) {
  this.object = object;
  }

  public Object get() {
  return object;
  }
  }

 

public class BoxDemo1 {

  public static void main(String[] args) {

  // ONLY place Integer objects into this box!
  Box integerBox = new Box();

  integerBox.add(new Integer(10));
  Integer someInteger = (Integer)integerBox.get();
  System.out.println(someInteger);
  }
}
The BoxDemo1 program creates an Integer object, passes it to add, then assigns that same object to someInteger by the return value of get. It then prints the object's value (10) to standard output. We know that the cast from Object to Integer is correct because we've honored the "contract" specified in the comment. But remember, the compiler knows nothing about this — it just trusts that our cast is correct. Furthermore, it will do nothing to prevent a careless programmer from passing in an object of the wrong type, such as String: 

public class BoxDemo2 {

  public static void main(String[] args) {

  // ONLY place Integer objects into this box!
  Box integerBox = new Box();

  // Imagine this is one part of a large application
  // modified by one programmer. 
  integerBox.add("10"); // note how the type is now String

  // ... and this is another, perhaps written
  // by a different programmer
  Integer someInteger = (Integer)integerBox.get();
  System.out.println(someInteger);
  }
}

What next?

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

Related Posts by Categories



0 comments: to “ generics introduction

Extension Factory Builder