<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:series="http://unfoldingneurons.com/"
	>

<channel>
	<title>Cyberward.net &#187; java</title>
	<atom:link href="http://www.cyberward.net/blog/tag/java/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.cyberward.net/blog</link>
	<description>The Drive Failures and Shutter Clicks of Christopher Ward</description>
	<lastBuildDate>Wed, 21 Jul 2010 12:00:15 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Intro to Java Observer Pattern</title>
		<link>http://www.cyberward.net/blog/2009/06/intro-to-java-observer-pattern/</link>
		<comments>http://www.cyberward.net/blog/2009/06/intro-to-java-observer-pattern/#comments</comments>
		<pubDate>Mon, 15 Jun 2009 16:27:07 +0000</pubDate>
		<dc:creator>Chris Ward</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[observer]]></category>
		<category><![CDATA[pattern]]></category>

		<guid isPermaLink="false">http://www.cyberward.net/blog/?p=1312</guid>
		<description><![CDATA[We are well into this whole patterns thing now, picking up lots of new lingo, and becoming better at communicating with other developers. Next on the list: the observer pattern. This is an important pattern to use to help prevent tight coupling and keep code separated into discrete objects. This pattern allows communication between two [...]]]></description>
			<content:encoded><![CDATA[<p>We are well into this whole patterns thing now, picking up lots of new lingo, and becoming better at communicating with other developers. Next on the list: the observer pattern. This is an important pattern to use to help prevent tight coupling and keep code separated into discrete objects. This pattern allows communication between two objects at particular times without each object needing to be too tightly coupled to the other.</p>
<h3>The Observer in the Physical World</h3>
<p>The idea behind the observer is like a subscription. Do you have a newspaper or magazine subscription? Have you signed up for cell phone texts from your favorite band when they have new tour dates? The act of you signing up with the newspaper, the magazine, or the band, is you saying you want a subscription, or that you want to become an observer. When the subject (newspaper, magazine, band) has something new to share (on a schedule or not) they run down their subscriber list, and notify the observers by mail, or text.</p>
<h3>The Observer in the Software World</h3>
<p>On the software side, the idea is the same. Your subject needs to provide a way to take subscriptions, hold a list of observers, and when a particular state changes, notify them. There is usually a couple of methods on the subject that takes in an interface that is used for getting on or off the subscription list. On this interface is also the &#8220;call back&#8221; method. This is the method that the subject will execute when it wants to inform the observers of state changes.<br />
<span id="more-1312"></span></p>
<h3>Do you have a picture?</h3>
<p><a href="http://www.cyberward.net/blog/wp-content/uploads/observercld.jpg"><img class="aligncenter wp-image-1313" title="observer pattern" src="http://www.cyberward.net/blog/wp-content/uploads/observercld.jpg" alt="observer pattern" width="500" height="241" /></a>¬†</p>
<p>Here is a class diagram for our first example. We have two classes and an interface. The interface, NumberObserver is the piece that connects the subject and the observer together. The NumberHolder class has methods to add and remove our observer from an internal list. The NumberDisplayer sets this object and the notify method on NumberHolder. The way it was implemented here was that NumberDisplayer implemented the interface. This is not the only way to do it. NumberDisplayer could create an inner class, or there could be an external class that implements the NumberObserver interface. It doesn&#8217;t matter. All that does matter is that NumberDisplayer passes a NumberObserver object to NumberHolder that implements the notifyNewNumber method. When NumberHolder changes it&#8217;s number, it then notifies all the observers by looping over the list it has of observers and executing the notifyNewNumber method on each one.</p>
<p>The NumberObserver is very basic. Just one method is defined here. The value that will be sent by the subject is the new number.</p>
<pre lang="java" name="NumberObserver.java" colla="+">
public interface NumberObserver {
   public void notifyNewNumber(int pNewValue);
   }
}
</pre>
<p>The NumberHolder doesn&#8217;t have much going on either. Most of the code is just to take care of the observers. Note the add, remove, and update observer methods.</p>
<pre lang="java" name="NumberHolder.java" colla="+">
public class NumberHolder {
   private int number;
   private List<NumberObserver> observerList;

   public NumberHolder() {
      number = 10;
      observerList = new ArrayList<NumberObserver>();
   }

   public void setNumber(int pNumber) {
      System.out.println("Number set to " + pNumber);
      number = pNumber;
      updateObservers();
   }

   public void addObserver(NumberObserver pObserver) {
      System.out.println("Adding observer:" + pObserver);
      observerList.add(pObserver);
   }

   public void removeObserver(NumberObserver pObserver) {
      System.out.println("Removing observer:" + pObserver);
      observerList.remove(pObserver);
   }

   private void updateObservers() {
      for (NumberObserver aObserver : observerList) {
         aObserver.notifyNewNumber(number);
      }
   }
}
</pre>
<p>And finally, the NumberDisplayer class that implements the NumberObserver interface.</p>
<pre lang="java" name="NumberDisplayer.java" colla="+">
public class NumberDisplayer implements NumberObserver {
   private String name;

   public NumberDisplayer(String pName) {
      name = pName;
   }

   public void notifyNewNumber(int pNewValue) {
      System.out.println(name + " is now displaying " + pNewValue);
   }
}
</pre>
<p>NumberHolderTest puts these three classes together. It creates several NumberDisplayer classes and adds and removes objects from the NumberHolder as well as updating the value. Run this to see the observer at work.</p>
<pre lang="Java" name="NumberHolderTest.java" colla="-">
public class NumberHolderTest {
   public static void main(String[] args) {
      NumberHolder aNumberHolder = new NumberHolder();

      // we can set the number at any time. Nothing happens because we don't
      // have any observers registered.
      aNumberHolder.setNumber(10);

      // Each NumberDisplayer will register with the NumberHolder
      NumberDisplayer aObserverAndDisplayerOne = new NumberDisplayer("One");
      aNumberHolder.addObserver(aObserverAndDisplayerOne);

      NumberDisplayer aObserverAndDisplayerTwo = new NumberDisplayer("Two");
      aNumberHolder.addObserver(aObserverAndDisplayerTwo);

      NumberDisplayer aObserverAndDisplayerThree = new NumberDisplayer("Three");
      aNumberHolder.addObserver(aObserverAndDisplayerThree);

      // Each NumberDisplayer should get notified of the change
      aNumberHolder.setNumber(20);

      // Remove two observers
      aNumberHolder.removeObserver(aObserverAndDisplayerOne);
      aNumberHolder.removeObserver(aObserverAndDisplayerTwo);

      // Now only one observer is left
      aNumberHolder.setNumber(30);
   }
}
</pre>
<p>The main idea here is that we can keep the two objects loosely coupled, with the one interface joining them together. The way this is done can vary a bit. In this particular case we have chosen to pass the new number. You could pass a different interface that exposed methods on the subject. You could just have a method that doesn&#8217;t pass anything if just need to know that something happened.</p>
<p>Let&#8217;s look at another example, this time using our Animal classes.</p>
<h3>Defining the problem</h3>
<p>We have a zoo. A zoo contains many cages, each cage contains several animals. The zoo keepers would like to have an up-to-date tally of all the animals in the zoo. Every time animals are added or removed from the cages, they want to know the totals. Let&#8217;s look at this without the observer pattern first.</p>
<h3>No Observer Pattern</h3>
<pre lang="Java" name="Cage1.java" colla="-">
public class Cage1<T extends Animal> {

   // List to hold our animals
   private List<T> animalList;

   public Cage1() {
      animalList = new ArrayList<T>();
   }

   public void insertAnimal(T pAnimal) {
      animalList.add(pAnimal);
      System.out.println("\n" + pAnimal.getName() + " " + pAnimal.getType()	+ " is added to the cage.");
   }

   public void removeAnimal(T pAnimal) {
      animalList.remove(pAnimal);
      System.out.println("\n" + pAnimal.getName() + " " + pAnimal.getType()	+ " is removed from the cage.");
   }

   public void clearCage() {
      animalList.clear();
   }

   public List<T> getAnimals() {
      return animalList;
   }
}
</pre>
<pre lang="Java" name="Zoo1.java" colla="-">
public class Zoo1 {
   private List<Cage1<? extends Animal>> cages;

   public Zoo1() {
      cages = new ArrayList<Cage1<? extends Animal>>();
   }

   public void addCage(Cage1<? extends Animal> pCage) {
      cages.add(pCage);
   }

   public void removeCage(Cage1<? extends Animal> pCage) {
      cages.remove(pCage);
   }

   public void doCageUpdated() {
      Map<String, Integer> aAnimalCounts = getAnimalCounts();
      displayAnimalCounts(aAnimalCounts);
   }

   public Map<String, Integer> getAnimalCounts() {
      Map<String, Integer> aAnimalCounts = new HashMap<String, Integer>();
      for (Cage1<? extends Animal> aCage : cages) {
         List<? extends Animal> aAnimalList = aCage.getAnimals();
         int aCount = aAnimalList.size();
         if (aCount > 0) {
            String aType = aAnimalList.get(0).getType();
            Integer aTypeCount = aAnimalCounts.get(aType);
            if (aTypeCount == null) {
               aTypeCount = new Integer(aCount);
            } else {
               aTypeCount = new Integer(aTypeCount.intValue() + aCount);
            }
            aAnimalCounts.put(aType, aTypeCount);
         }
      }
      return aAnimalCounts;
}

   public void displayAnimalCounts(Map<String, Integer> animalCounts) {

      Set<String> aAnimalSet = animalCounts.keySet();
      if (aAnimalSet == null || aAnimalSet.isEmpty()) {
         System.out.println("\nZoo is currently empty.");
      } else {
         System.out.println("\nCurrent zoo animal counts:");
      }
      for (String aType : aAnimalSet) {
         Integer aTypeCount = animalCounts.get(aType);
         System.out.println("There are " + aTypeCount.intValue() + " of type " + aType);
      }
   }
}
</pre>
<p>See Cage1.java. Pretty simple. Just a simple list, and the methods to support getting data in and out of the list. Now look at Zoo1.java. This class contains the cages in a List. It also has the methods that can look at all the cages and create the totals for each animal type.</p>
<p>There is also a method doCageUpdated that must be called everytime an animal is added to a cage. The way we have this set up so far, there is no way for the zoo to know when an animal is added to a cage. A cage knows where an animal is added, but the cage doesn&#8217;t know about the zoo. It is contained within the zoo, but there is no coupling between the cage, and the zoo. We could insert a reverence for the zoo into the cage when the cages are added to the zoo, but we try to avoid this circular coupling.</p>
<pre lang="Java" name="ZooTest1.java" colla="-">
public class ZooTest1 {
   public static void main(String[] args) {

      Zoo1 aZoo = new Zoo1();

      Cage1<Bird> aBirdCage = new Cage1<Bird>();
      aZoo.addCage(aBirdCage);

      aBirdCage.insertAnimal(new Bird());
      // tell zoo to check counts and update display
      aZoo.doCageUpdated();

      aBirdCage.insertAnimal(new Bird());
      // tell zoo to check counts and update display
      aZoo.doCageUpdated();

      Cage1<Mammal> aMammalCage = new Cage1<Mammal>();
      aZoo.addCage(aMammalCage);
      // tell zoo to check counts and update display
      aZoo.doCageUpdated();

      Mammal aFred = new Mammal("Fred");
      aMammalCage.insertAnimal(aFred);
      // tell zoo to check counts and update display
      aZoo.doCageUpdated();

      Cage1<Mammal> aDogCage = new Cage1<Mammal>();
      aZoo.addCage(aDogCage);

      aDogCage.insertAnimal(new Mammal("Rover"));
      // tell zoo to check counts and update display
      aZoo.doCageUpdated();

      aDogCage.insertAnimal(new Mammal("Spot"));
      // tell zoo to check counts and update display
      aZoo.doCageUpdated();

      aMammalCage.removeAnimal(aFred);
      // tell zoo to check counts and update display
      aZoo.doCageUpdated();

      aBirdCage.clearCage();
      // tell zoo to check counts and update display
      aZoo.doCageUpdated();

      aDogCage.clearCage();
      // tell zoo to check counts and update display
      aZoo.doCageUpdated();
   }
}
</pre>
<p>What we are forced to do, and must rely on, is that the developer writing the program will call the doCageUpdated() method on the zoo object every time an animal is added to a cage. See ZooTest1.java. This is not good programming practice.</p>
<h3>Implementing the Observer Pattern</h3>
<pre lang="Java" name="Cage2.java" colla="-">
public class Cage2<T extends Animal> {
   // List to hold our animals
   private List<T> animalList;

   // List to hold our observers
   private List<CageObserver> cageObservers;

   public Cage2() {
      animalList = new ArrayList<T>();
      cageObservers = new ArrayList<CageObserver>();
   }

   public void insertAnimal(T pAnimal) {
      animalList.add(pAnimal);
      System.out.println("\n" + pAnimal.getName() + " " + pAnimal.getType()	+ " is added to the cage.");
      notifyObservers();
   }

   public void removeAnimal(T pAnimal) {
      animalList.remove(pAnimal);
      System.out.println("\n" + pAnimal.getName() + " " + pAnimal.getType()	+ " is removed from the cage.");
      notifyObservers();
   }

   public void clearCage() {
      animalList.clear();
      notifyObservers();
   }

   public List<T> getAnimals() {
      return animalList;
   }

   public void addCageObserver(CageObserver pCageObserver) {
      cageObservers.add(pCageObserver);
   }

   public void removeCageObserver(CageObserver pCageObserver) {
      cageObservers.remove(pCageObserver);
   }

   private void notifyObservers() {
      for (CageObserver aCageObserver : cageObservers) {
         aCageObserver.doCageUpdated();
      }
   }
}
</pre>
<pre lang="Java" name="Zoo2.java" colla="-">
public class Zoo2 implements CageObserver {
   private List<Cage2<? extends Animal>> cages;

   public Zoo2() {
      cages = new ArrayList<Cage2<? extends Animal>>();
   }

   public void addCage(Cage2<? extends Animal> pCage) {
      pCage.addCageObserver(this);
      cages.add(pCage);
   }

   public void removeCage(Cage2<? extends Animal> pCage) {
      pCage.removeCageObserver(this);
      cages.remove(pCage);
   }

   public void doCageUpdated() {
      Map<String, Integer> aAnimalCounts = getAnimalCounts();
      displayAnimalCounts(aAnimalCounts);
   }

   public Map<String, Integer> getAnimalCounts() {
      Map<String, Integer> aAnimalCounts = new HashMap<String, Integer>();
      for (Cage2<? extends Animal> aCage : cages) {
         List<? extends Animal> aAnimalList = aCage.getAnimals();
         int aCount = aAnimalList.size();
         if (aCount > 0) {
            String aType = aAnimalList.get(0).getType();
            Integer aTypeCount = aAnimalCounts.get(aType);
            if (aTypeCount == null) {
               aTypeCount = new Integer(aCount);
            } else {
               aTypeCount = new Integer(aTypeCount.intValue() + aCount);
            }
            aAnimalCounts.put(aType, aTypeCount);
         }
      }
      return aAnimalCounts;
   }

   public void displayAnimalCounts(Map<String, Integer> animalCounts) {

      Set<String> aAnimalSet = animalCounts.keySet();
      if (aAnimalSet == null || aAnimalSet.isEmpty()) {
         System.out.println("\nZoo is currently empty.");
      } else {
         System.out.println("\nCurrent zoo animal counts:");
      }
      for (String aType : aAnimalSet) {
         Integer aTypeCount = animalCounts.get(aType);
         System.out.println("There are " + aTypeCount.intValue() + " of type " + aType);
      }
   }
}
</pre>
<p>A better way is to implement the observer pattern. Look at Cage2.java, Zoo2.java, and ZooTest2.java. Looking at Cage2.java you can see that the Cage2 class now has another list, the list of CageObserver&#8217;s. Now, when an animal is added to the cage, the cage informs anyone that is listening that the cage count has changed. In our case, we just send a message that the cage is updated, but in a different design you may have passed the Cage2 object its self, or an interface, or another object that indicated the type of event (add, remove, clear) and the number of animals that it evolved. That is all up to your design. They would all fit the observer pattern.</p>
<pre lang="Java" name="ZooTest2.java" colla="-">
public class ZooTest2 {
   public static void main(String[] args) {

      Zoo2 aZoo = new Zoo2();

      Cage2<Bird> aBirdCage = new Cage2<Bird>();
      aZoo.addCage(aBirdCage);

      aBirdCage.insertAnimal(new Bird());
      aBirdCage.insertAnimal(new Bird());

      Cage2<Mammal> aMammalCage = new Cage2<Mammal>();
      aZoo.addCage(aMammalCage);

      Mammal aFred = new Mammal("Fred");
      aMammalCage.insertAnimal(aFred);

      Cage2<Mammal> aDogCage = new Cage2<Mammal>();
      aZoo.addCage(aDogCage);

      aDogCage.insertAnimal(new Mammal("Rover"));
      aDogCage.insertAnimal(new Mammal("Spot"));

      aMammalCage.removeAnimal(aFred);

      aBirdCage.clearCage();
      aDogCage.clearCage();
   }
}
</pre>
<p>Now look at the ZooTest2 class. Much better. No longer do we have to tell the zoo to display the data, it is done automatically. This may not seem that worthwhile here, but the process for adding cages to the zoo may not be connected with the process of adding animals to anyone cage. Keeping these things separate allows for more flexibility.</p>
<h3>Swinging the Observer Pattern</h3>
<p>We have already used the observer pattern in a previous lesson. Way back when we covered classes we looked at creating a Gui and implemented a WindowListener. We didn&#8217;t discuss it back then, but we were implementing the Observer Pattern. That&#8217;s right, every time we register an action listener of some sort in AWT, or Swing, we are registering an Observer with a Subject. Go back and look at Gui1 to Gui4. These are 4 different ways of creating the Observing class. As an example, here is Gui3.java.</p>
<pre lang="Java" name="Gui3.java" colla="+">
public class Gui3 extends JFrame {
   public Gui3() {
      setTitle("Gui3");
      setSize(300, 300);
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.out.println("Closeing Gui3");
            System.exit(0);
         }
      });
   }

   public static void main(String[] args) {
      JFrame aFrame = new Gui3();
      aFrame.setVisible(true);
   }
}
</pre>
<p>So keep this in mind. If you have written a GUI program, it is almost certain that you have implemented the Observer pattern. Swing depends heavily on it. That is how your visual components can react when users press buttons, move focus, and close windows. This way, you don&#8217;t have to create a loop of code that checks for a mouse click, and then determine which button the mouse was over, and then directs the program flow to specific code handling sections. You simple register with each button to be informed when it is clicked. And remember, several objects can register to listen at the same time. Because of this, Java even has a solution you can implement, called the EventListenerList. You can use this list in your classes to implement event listeners. Why reinvent it your self if it is already provided. This class supplies the underlying list, and methods to add and remove EventListeners to and from the List. It doesn&#8217;t supply a method to notify listeners in the list, but it does provide a method (getListeners()) that can take in a class type parameter so that you can ask the list to return just the listeners of a particular type. If you find you need to implement an observer event list, check this class out.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cyberward.net/blog/2009/06/intro-to-java-observer-pattern/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Intro to Java Decorator Pattern</title>
		<link>http://www.cyberward.net/blog/2009/06/intro-to-java-decorator-pattern/</link>
		<comments>http://www.cyberward.net/blog/2009/06/intro-to-java-decorator-pattern/#comments</comments>
		<pubDate>Tue, 09 Jun 2009 19:01:36 +0000</pubDate>
		<dc:creator>Chris Ward</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[decorator]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[pattern]]></category>

		<guid isPermaLink="false">http://www.cyberward.net/blog/?p=1284</guid>
		<description><![CDATA[We have looked at the Factory, the Adapter, and the Singleton patterns. Now we look at the Decorator. The Decorator is similar to the Adapter, but with a subtle difference. With our ReptileAdapter, we wrapped the Reptile class to map the interface methods of Animal to the appropriate methods on Reptile. With the Decorator we [...]]]></description>
			<content:encoded><![CDATA[<p>We have looked at the Factory, the Adapter, and the Singleton patterns. Now we look at the Decorator. The Decorator is similar to the Adapter, but with a subtle difference. With our ReptileAdapter, we wrapped the Reptile class to map the interface methods of Animal to the appropriate methods on Reptile. With the Decorator we also wrap a class, but to add functionality, not to map it or replace the functionality.</p>
<h3>The Decorator in the Physical World</h3>
<p>The idea behind decorating things in the real world is pretty much how it sounds. We wrap an object with new functionality, while keeping the old functionality. How about a camera in a waterproof housing? When closed up, we have added the functionality of waterproofing, but we still provide a way to press the buttons and turn the dials so that the camera can be operated.</p>
<h3>The Decorator in the Software World</h3>
<p>On the software side, the idea is the same. It is usually used when we have one object that we like how it functions, but we want to augment the behavior for a different situation. Done correctly, we can keep inserting one object inside another adding functionality at every step.<br />
<span id="more-1284"></span></p>
<h3>What do we need to create a Decorator?</h3>
<p>We need to create a class (our Decorator) that contains the class we want to decorate. We usually get this class into the Decorator using a constructor. Our Decorator needs to extend or implement the class or interface that contains the functionality we want to Decorate. Then when one of the methods of the decorated class is called, we call it before or after adding our own functionality.</p>
<h3>Ummm, Example?</h3>
<p>Lets use our Animals again. We are going to get a little bit emotional, or at least our animals are. Have you ever met people, who no matter what you ask them, has to tell you their emotional state? We will create an animal decorator that does just that. Every time we ask them to move() or speak() they will still move and speak, but they will also tell us their emotional state.</p>
<p>So, how do we accomplish this? Just as we could have done when we started looking at the Adapter, we could just go into the code for Animal or BaseAnimal and add new code to store a feeling, and put some getters and setters on it. But, our Animal code works, and not every animal likes to tell everyone they meet what they are feeling.</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1284code14'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p128414"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
</pre></td><td class="code" id="p1284code14"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">abstract</span> <span style="color: #000000; font-weight: bold;">class</span> EmotionDecorator <span style="color: #000000; font-weight: bold;">extends</span> BaseAnimal <span style="color: #009900;">&#123;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">private</span> Animal decoratedAnimal<span style="color: #339933;">;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> EmotionDecorator<span style="color: #009900;">&#40;</span>Animal pDecoratedAnimal<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      decoratedAnimal <span style="color: #339933;">=</span> pDecoratedAnimal<span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a> getType<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">return</span> decoratedAnimal.<span style="color: #006633;">getType</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> move<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      decoratedAnimal.<span style="color: #006633;">move</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      showEmotion<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> speak<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      decoratedAnimal.<span style="color: #006633;">speak</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      showEmotion<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">void</span> showEmotion<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Asystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">System</span></a>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;(Who by the way, is very &quot;</span> <span style="color: #339933;">+</span> getEmotion<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;.)&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">abstract</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a> getEmotion<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>So, we start by extending BaseAnimal. This means that we get all the functionality that is in BaseAnimal, and means that other objects can just treat us like an Animal. (BaseAnimal implements the Animal interface). We have a constructor that takes in an Animal to be decorated. Not every method is implemented by BaseAnimal however, so we provide the pass thru method for getType() and decorate move() and speak().</p>
<p>The getType() method does not add anything, but we still need to provide this pass thru method, because we want the decorated Animal&#8217;s type to be returned if someone asks us.</p>
<p>The move() and speak() methods get decorated. We first call the method on our decorated Animal, then we call showEmotion(). This does the same thing for both, it prints out how the animal is feeling. It gets its emotion from an abstract method. This allows us to push down the hierarchy to some small concrete classes just the specific behavior for each emotion. This does mean a different emotion class for each emotion, but it can be used for all animals. As an exercise, when this is over, try to create a EmotionDecorator that takes in a parameter for the emotion type instead.</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1284code15'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p128415"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
</pre></td><td class="code" id="p1284code15"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> HappyDecorator <span style="color: #000000; font-weight: bold;">extends</span> EmotionDecorator <span style="color: #009900;">&#123;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> HappyDecorator<span style="color: #009900;">&#40;</span>Animal pDecoratedAnimal<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">super</span><span style="color: #009900;">&#40;</span>pDecoratedAnimal<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a> getEmotion<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #0000ff;">&quot;happy&quot;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
Nothing to it. <span style="color: #006633;">It</span> just creates the constructor so our decorated animal is set up, and provides the correct emotion.
&nbsp;
<span style="color: #006633;">Lets</span> see an example of how we construct <span style="color: #000000; font-weight: bold;">this</span> decorator now.
<span style="color: #339933;">&lt;</span>pre lang<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;Java&quot;</span><span style="color: #339933;">&gt;</span>public <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> main<span style="color: #009900;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> args<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
   Animal aBird <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Bird<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   Animal aHappyBird <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> HappyDecorator<span style="color: #009900;">&#40;</span>aBird<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
   aBird.<span style="color: #006633;">move</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   aHappyBird.<span style="color: #006633;">move</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Here we create a Bird and we create a HappyDecorator that we put the bird into. If we call move() on aBird, we just get the move() method on bird. If we call the move() method on aHappyBird, we get the Bird.move() method called and the decoration.</p>
<p>We don&#8217;t have to create and hold an instance of Bird. We could just add them by doing a new inside the constructor of our decorator. We can even chain our emotions together to get one confused bird.</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1284code16'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p128416"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code" id="p1284code16"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> main<span style="color: #009900;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> args<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
   Animal aAngryBird <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> AngryDecorator<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Bird<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   Animal aHappyBird <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> HappyDecorator<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Bird<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   Animal aConfusedBird <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> AngryDecorator<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> HappyDecorator<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Bird<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
   aAngryBird.<span style="color: #006633;">move</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   aHappyBird.<span style="color: #006633;">move</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   aConfusedBird.<span style="color: #006633;">move</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>And just so you can see that we can decorate any of our Animals:</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1284code17'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p128417"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code" id="p1284code17"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> main<span style="color: #009900;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> args<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
   Animal aAngryBird <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> AngryDecorator<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Bird<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   Animal aHappyFish <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> HappyDecorator<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Fish<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   Animal aConfusedMammal <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> AngryDecorator<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> HappyDecorator<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Mammal<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
   aAngryBird.<span style="color: #006633;">move</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   aHappyFish.<span style="color: #006633;">move</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   aConfusedMammal.<span style="color: #006633;">move</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>The chaining thing doesn&#8217;t look all that useful in this context, but it can be a great tool. Lets take a quick look at another example, the MovingDecorator. This is almost the same implementation as the EmotionDecorator, but we are only going to decorate the move() method. Lets throw a new twist in there too. Often with a Decorator, there is some sort of setup or initialization to do, so lets allow a way to init this decorator with a value, and have an abstract method to provide the values expected type.</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1284code18'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p128418"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
</pre></td><td class="code" id="p1284code18"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">abstract</span> <span style="color: #000000; font-weight: bold;">class</span> MovingDecorator <span style="color: #000000; font-weight: bold;">extends</span> BaseAnimal <span style="color: #009900;">&#123;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">private</span> Animal decoratedAnimal<span style="color: #339933;">;</span>
   <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">int</span> movementAmount<span style="color: #339933;">;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> MovingDecorator<span style="color: #009900;">&#40;</span>Animal pDecoratedAnimal<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      decoratedAnimal <span style="color: #339933;">=</span> pDecoratedAnimal<span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> init<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> pMovementAmount<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      movementAmount <span style="color: #339933;">=</span> pMovementAmount<span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a> getType<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">return</span> decoratedAnimal.<span style="color: #006633;">getType</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> move<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      decoratedAnimal.<span style="color: #006633;">move</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astringwriter+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">StringWriter</span></a> aWriter <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astringwriter+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">StringWriter</span></a><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      aWriter.<span style="color: #006633;">append</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Move &quot;</span> <span style="color: #339933;">+</span> getMovement<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>movementAmount <span style="color: #339933;">!=</span> <span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
         aWriter.<span style="color: #006633;">append</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot; &quot;</span> <span style="color: #339933;">+</span> movementAmount<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
         aWriter.<span style="color: #006633;">append</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot; &quot;</span> <span style="color: #339933;">+</span> getMovementUnits<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #009900;">&#125;</span>
      aWriter.<span style="color: #006633;">append</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;.&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Asystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">System</span></a>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span>aWriter.<span style="color: #006633;">toString</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> speak<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      decoratedAnimal.<span style="color: #006633;">speak</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">abstract</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a> getMovement<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">abstract</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a> getMovementUnits<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>We now have a more complicated move method, but the idea is much the same. Decorate the object, then add functionality.</p>
<p>Once again we need to create concrete methods for the movement types. We have MoveForward, MoveLeft, and MoveRight.</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1284code19'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p128419"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
</pre></td><td class="code" id="p1284code19"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> MoveRightDecorator <span style="color: #000000; font-weight: bold;">extends</span> MovingDecorator <span style="color: #009900;">&#123;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> MoveRightDecorator<span style="color: #009900;">&#40;</span>Animal pDecoratedAnimal<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">super</span><span style="color: #009900;">&#40;</span>pDecoratedAnimal<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a> getMovement<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #0000ff;">&quot;right&quot;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a> getMovementUnits<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #0000ff;">&quot;degrees&quot;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>These look almost the same as our Emotion ones, but we also have to implement a movement units method.</p>
<p>For our purposes we didn&#8217;t have to execute the init method, but we could. First is a simple class showing the using of this Decorator.</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1284code20'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p128420"><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code" id="p1284code20"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> main<span style="color: #009900;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> args<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
   Animal aMammal <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> MoveForwardDecorator<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Mammal<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   aMammal.<span style="color: #006633;">move</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Here shows chaining the move methods:</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1284code21'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p128421"><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code" id="p1284code21"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> main<span style="color: #009900;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> args<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
   Animal aBird <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> MoveForwardDecorator<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> MoveLeftDecorator<span style="color: #009900;">&#40;</span>
   <span style="color: #000000; font-weight: bold;">new</span> MoveForwardDecorator<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> MoveRightDecorator<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Fish<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   aBird.<span style="color: #006633;">move</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>And finally, here we use the init method:</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1284code22'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p128422"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
</pre></td><td class="code" id="p1284code22"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> main<span style="color: #009900;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> args<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
   Animal aBird <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Bird<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   MovingDecorator aDecoBird <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> MoveForwardDecorator<span style="color: #009900;">&#40;</span>aBird<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   aDecoBird.<span style="color: #006633;">init</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">10</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   aDecoBird <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> MoveRightDecorator<span style="color: #009900;">&#40;</span>aDecoBird<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   aDecoBird <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> MoveForwardDecorator<span style="color: #009900;">&#40;</span>aDecoBird<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   aDecoBird <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> MoveLeftDecorator<span style="color: #009900;">&#40;</span>aDecoBird<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   aDecoBird.<span style="color: #006633;">init</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">90</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   aDecoBird <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> MoveForwardDecorator<span style="color: #009900;">&#40;</span>aDecoBird<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
   <span style="color: #666666; font-style: italic;">//What happens when this is uncommented?</span>
   <span style="color: #666666; font-style: italic;">//aDecoBird = new HappyDecorator(aBird);</span>
&nbsp;
   aDecoBird.<span style="color: #006633;">move</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   aDecoBird.<span style="color: #006633;">speak</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>If you noticed, I actually created a MovingDecorator instead of an Animal here, and that was simply so that I didn&#8217;t have to keep casting to call the init method.</p>
<h3>How about in the Java SDK?</h3>
<p>One of the best examples is the FileIO section. This is the code that allows you to read and write to the file system. You start with a basic byte or character reader, then wrap with decorators that can read by lines, or buffer for more performance.</p>
<p>You can learn about file IO in this <a href="http://java.sun.com/docs/books/tutorial/essential/io/">sun trail</a>.</p>
<p>If you remember from the Reflection Session, we read data from a properties file. We will access a file the same way here. This is shown so you can see what it looks like with no decoration.</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1284code23'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p128423"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
</pre></td><td class="code" id="p1284code23"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> IODecoratorTest1 <span style="color: #009900;">&#123;</span>
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> main<span style="color: #009900;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> args<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Aexception+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">Exception</span></a> <span style="color: #009900;">&#123;</span>
&nbsp;
      <span style="color: #000066; font-weight: bold;">int</span> c<span style="color: #339933;">;</span>
&nbsp;
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Ainputstream+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">InputStream</span></a> aStream <span style="color: #339933;">=</span> IODecoratorTest1.<span style="color: #000000; font-weight: bold;">class</span>.<span style="color: #006633;">getResourceAsStream</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;ioTest.txt&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
      <span style="color: #000000; font-weight: bold;">while</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span> c <span style="color: #339933;">=</span> aStream.<span style="color: #006633;">read</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span> <span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;=</span> <span style="color: #cc66cc;">0</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
         <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Asystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">System</span></a>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">char</span><span style="color: #009900;">&#41;</span>c<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #009900;">&#125;</span>
&nbsp;
      aStream.<span style="color: #006633;">close</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>IODecoratorTest2 shows how we decorate the input stream. First with InputStreamReader, then with BufferedReader, then finally adding a LineNumberReader.</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1284code24'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p128424"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="code" id="p1284code24"><pre class="java" style="font-family:monospace;"><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Areader+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">Reader</span></a> aReader <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Ainputstreamreader+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">InputStreamReader</span></a><span style="color: #009900;">&#40;</span>IODecoratorTest1.<span style="color: #000000; font-weight: bold;">class</span>
.<span style="color: #006633;">getResourceAsStream</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;ioTest.txt&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Areader+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">Reader</span></a> aReader <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Abufferedreader+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">BufferedReader</span></a><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Ainputstreamreader+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">InputStreamReader</span></a><span style="color: #009900;">&#40;</span>
IODecoratorTest1.<span style="color: #000000; font-weight: bold;">class</span>.<span style="color: #006633;">getResourceAsStream</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;ioTest.txt&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Areader+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">Reader</span></a> aReader <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Alinenumberreader+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">LineNumberReader</span></a><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Abufferedreader+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">BufferedReader</span></a><span style="color: #009900;">&#40;</span>
<span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Ainputstreamreader+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">InputStreamReader</span></a><span style="color: #009900;">&#40;</span>IODecoratorTest2.<span style="color: #000000; font-weight: bold;">class</span>
.<span style="color: #006633;">getResourceAsStream</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;ioTest.txt&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>So, as you can see, we are layering, or stacking the classes. We are decorating the read() methods in each of these classes to add behavior. We can do the same thing. Lets write a Reader decorator ourselves that can count the number of times ‚ÄòI&#8217; is in the file.</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1284code25'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p128425"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
</pre></td><td class="code" id="p1284code25"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> ICountReader <span style="color: #000000; font-weight: bold;">extends</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Afilterreader+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">FilterReader</span></a> <span style="color: #009900;">&#123;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">private</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Areader+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">Reader</span></a> inReader<span style="color: #339933;">;</span>
   <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">int</span> count<span style="color: #339933;">;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> ICountReader<span style="color: #009900;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Areader+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">Reader</span></a> pInReader<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">super</span><span style="color: #009900;">&#40;</span>pInReader<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      inReader <span style="color: #339933;">=</span> pInReader<span style="color: #339933;">;</span>
      count <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">int</span> read<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Aioexception+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">IOException</span></a> <span style="color: #009900;">&#123;</span>
      <span style="color: #000066; font-weight: bold;">int</span> aByte <span style="color: #339933;">=</span> inReader.<span style="color: #006633;">read</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>aByte <span style="color: #339933;">==</span> <span style="color: #0000ff;">'I'</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
         count<span style="color: #339933;">++;</span>
      <span style="color: #009900;">&#125;</span>
      <span style="color: #000000; font-weight: bold;">return</span> aByte<span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">int</span> read<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">char</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> cbuf, <span style="color: #000066; font-weight: bold;">int</span> off, <span style="color: #000066; font-weight: bold;">int</span> len<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Aioexception+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">IOException</span></a> <span style="color: #009900;">&#123;</span>
      <span style="color: #000066; font-weight: bold;">int</span> n <span style="color: #339933;">=</span> inReader.<span style="color: #006633;">read</span><span style="color: #009900;">&#40;</span>cbuf, off, len<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
      <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> i <span style="color: #339933;">=</span> off<span style="color: #339933;">;</span> i <span style="color: #339933;">&amp;</span>lt<span style="color: #339933;">;</span> off <span style="color: #339933;">+</span> n<span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
         <span style="color: #000066; font-weight: bold;">int</span> c <span style="color: #339933;">=</span> cbuf<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
         <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>c <span style="color: #339933;">==</span> <span style="color: #0000ff;">'I'</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            count<span style="color: #339933;">++;</span>
         <span style="color: #009900;">&#125;</span>
      <span style="color: #009900;">&#125;</span>
   <span style="color: #000000; font-weight: bold;">return</span> n<span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">int</span> getICount<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">return</span> count<span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>We are extending FilterReader instead of implementing the Reader interface so we don&#8217;t have quite so many methods to implement. This is just the same as the other decorators we have been looking at. We can insert it into a decorator chain just the same way.</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1284code26'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p128426"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
</pre></td><td class="code" id="p1284code26"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> IODecoratorTest3 <span style="color: #009900;">&#123;</span>
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> main<span style="color: #009900;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> args<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Aexception+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">Exception</span></a> <span style="color: #009900;">&#123;</span>
      <span style="color: #000066; font-weight: bold;">int</span> c<span style="color: #339933;">;</span>
      ICountReader aICountReader <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ICountReader<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Abufferedreader+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">BufferedReader</span></a><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Ainputstreamreader+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">InputStreamReader</span></a><span style="color: #009900;">&#40;</span>IODecoratorTest1.<span style="color: #000000; font-weight: bold;">class</span>.<span style="color: #006633;">getResourceAsStream</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;ioTest.txt&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Alinenumberreader+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">LineNumberReader</span></a> aLineReader <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Alinenumberreader+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">LineNumberReader</span></a><span style="color: #009900;">&#40;</span>aICountReader<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
      <span style="color: #000000; font-weight: bold;">while</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>c <span style="color: #339933;">=</span> aLineReader.<span style="color: #006633;">read</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;=</span> <span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
          <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Asystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">System</span></a>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">char</span><span style="color: #009900;">&#41;</span> c<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #009900;">&#125;</span>
&nbsp;
      aLineReader.<span style="color: #006633;">close</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
      <span style="color: #666666; font-style: italic;">// We cast because we need a ICountRe to ask for the line</span>
      <span style="color: #666666; font-style: italic;">// number, and it is zero based so we add one</span>
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Asystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">System</span></a>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;# of I's:&quot;</span> <span style="color: #339933;">+</span> aICountReader.<span style="color: #006633;">getICount</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Asystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">System</span></a>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;# of lines:&quot;</span> <span style="color: #339933;">+</span> <span style="color: #009900;">&#40;</span>aLineReader.<span style="color: #006633;">getLineNumber</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.cyberward.net/blog/2009/06/intro-to-java-decorator-pattern/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<series:name><![CDATA[Intro to Java]]></series:name>
	</item>
		<item>
		<title>Intro to Java Singleton Pattern</title>
		<link>http://www.cyberward.net/blog/2009/06/intro-to-java-singleton-pattern/</link>
		<comments>http://www.cyberward.net/blog/2009/06/intro-to-java-singleton-pattern/#comments</comments>
		<pubDate>Mon, 08 Jun 2009 21:53:37 +0000</pubDate>
		<dc:creator>Chris Ward</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[patterns]]></category>
		<category><![CDATA[singleton]]></category>

		<guid isPermaLink="false">http://www.cyberward.net/blog/?p=1273</guid>
		<description><![CDATA[The last pattern we looked at was the Adapter pattern. It was a good pattern to start with as it maps well to the physical world and is fairly simple. Now we will look at the Singleton pattern. In some respects it is the simplest of patterns, but there are some things to think about.
The [...]]]></description>
			<content:encoded><![CDATA[<p>The last pattern we looked at was the Adapter pattern. It was a good pattern to start with as it maps well to the physical world and is fairly simple. Now we will look at the Singleton pattern. In some respects it is the simplest of patterns, but there are some things to think about.</p>
<h3>The Singleton in the Physical World</h3>
<p>The idea behind the Singleton is to ensure that there can be only one (insert Highlander jokes here). If you had a factory that made widgets, you would want a widget to be created many many times. But there is only one factory. If you were modeling the US government, you would only want one president. Only one senate.</p>
<h3>The Singleton in the Software World</h3>
<p>On the software side, the idea is the same. It is usually used when we only want one set of configuration variables, one controller, one data base connection pool, that kind of thing.<br />
<span id="more-1273"></span></p>
<h3>How do we do this?</h3>
<p>Let&#8217;s back up a bit. Let us look at a very basic class that provides us with a code that is needed across our application.</p>
<pre lang="Java" name="MyClass.java" colla="+">
public class MyClass {

   private long code;

   public MyClass() {
      code = Calendar.getInstance().getTimeInMillis();
   }

   public long getCode() {
      return code;
   }
}
</pre>
<pre lang="Java" name="MyClassTest.java" colla="-">
public class MyClassTest {
   public static void main(String[] args) throws Exception {

      MyClass myClass1 = new MyClass();
      System.out.println(myClass1.getCode());

      Thread.sleep(500);// wait a bit to see if our code is the same

      MyClass myClass2 = new MyClass();
      System.out.println(myClass2.getCode());

      System.out.println("Oops. Different values.");
   }
}
</pre>
<p>If you only ever instantiated this class once, you are fine. But we haven&#8217;t done anything here to ensure that this is the case. There is nothing to stop someone from creating two MyClass objects.</p>
<p>Let&#8217;s start with the opposite. How do we create an instance of a class?</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1273code29'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p127329"><td class="line_numbers"><pre>1
2
</pre></td><td class="code" id="p1273code29"><pre class="java" style="font-family:monospace;">MyClass myClass1 <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> MyClass<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
MyClass myClass2 <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> MyClass<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>What can we do to ensure that only one instance can be created? Is there something else we have looked at that allows only one instance of a variable to occur? Static! We can use the static property.</p>
<pre lang="Java" name="MyStaticClass.java" colla="+">
public class MyStaticClass {

   private static long code = Calendar.getInstance().getTimeInMillis();

   public static long getCode() {
      return code;
   }
}
</pre>
<pre lang="Java" name="MyStaticClassTest.java" colla="-">
   public static void main(String[] args) throws Exception {

      MyStaticClass myClass1 = new MyStaticClass();
      System.out.println(MyStaticClass.getCode());
      System.out.println(myClass1);

      Thread.sleep(500);// wait a bit to make sure our code is the same

      MyStaticClass myClass2 = new MyStaticClass();
      System.out.println(MyStaticClass.getCode());
      System.out.println(myClass2);

      System.out.println("Ok. Same values.");
      System.out.println("Oops, different objects.");

   }
}
</pre>
<p>This time we have assigned a static variable our code, and provided a static method for accessing this code. Does this work? Somewhat. We only have one instance of code inside of MyStaticClass, but MyStaticClass is not guaranteed to have only one instance. This will get cumbersome to initialize as we add other data. It also results in a bunch of MyStaticClass.getCode() all over the application. What would be better would be to ask for this class just once, and then call getCode() as needed. How can we set that up?</p>
<h3>The Simplest Singleton</h3>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1273code30'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p127330"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
</pre></td><td class="code" id="p1273code30"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Singleton <span style="color: #009900;">&#123;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> Singleton singleton<span style="color: #339933;">;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">private</span> Singleton<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> Singleton getInstance<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span> singleton <span style="color: #339933;">==</span> <span style="color: #000066; font-weight: bold;">null</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
         singleton <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Singleton<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #009900;">&#125;</span>
      <span style="color: #000000; font-weight: bold;">return</span> singleton<span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>This example doesn&#8217;t have our &#8220;code&#8221; in it, but it does show the elements of the singleton. We will add the &#8220;code&#8221; later.</p>
<p>There are some interesting things about this class. Look at the constructor. It is private! How does that work? We can&#8217;t do a &#8220;new&#8221; on this class! How can we create it? There is a private member variable that is static, and is of the same type as the class! It is a very strange sight at first glance. What is going on?</p>
<p>The constructor being private accounts for our first goal. No ability to call &#8220;new&#8221; on the object. If we can&#8217;t do a &#8220;new&#8221;, how can we create it? Well, we can do a &#8220;new&#8221;, but only from inside the class itself. We are doing that in the static getInstance() method. Look at what that method does. It first checks to see if an instance of the member variable singleton exists. If it doesn&#8217;t, it creates a &#8220;new&#8221; instance. This is the only place we will ever create an instance of the class Singleton. Therefore we have ensured that this is the only copy available. We then return singleton.</p>
<p>By doing things this way we have also lazy initialized the singleton. If we don&#8217;t need it, we never call getInstance(), and we never have to worry about the JVM allocating memory for something not used.</p>
<p>We also get a normal looking class out of it. We can have standard getters that are not static, and our application can pass this object around. It is easier to conceptualize the object used this way, and do maintenance later than a bunch of static methods seemingly randomly called within methods.</p>
<h3>Can we actually do something?</h3>
<p>Ok, I get your point. We need a bit more of an example. So here is a singleton with one &#8220;code&#8221; just like the others.</p>
<pre lang="Java" name="MySingletonClass.java" colla="+">
public class MySingletonClass {

   private static MySingletonClass singleton;

   private long code;

   private MySingletonClass() {
      code = Calendar.getInstance().getTimeInMillis();
   }

   public static MySingletonClass getInstance() {

      if ( singleton == null ) {
         singleton = new MySingletonClass();
      }
      return singleton;
   }

   public long getCode() {
      return code;
   }
}
</pre>
<pre lang="Java" name="MySingletonClassTest.java" colla="-">
public class MySingletonClassTest {
   public static void main(String[] args) throws Exception {

      MySingletonClass mySingletonClass1 = MySingletonClass.getInstance();
      System.out.println(mySingletonClass1.getCode());
      System.out.println(mySingletonClass1);

      Thread.sleep(500); //wait a bit to make sure our code is the same

      MySingletonClass mySingletonClass2 = MySingletonClass.getInstance();
      System.out.println(mySingletonClass2.getCode());
      System.out.println(mySingletonClass2);

      System.out.println("yea, same code");
      System.out.println("yea, same object");
   }
}
</pre>
<p>Look at that. Other than the singleton field, the constructor marked as private, and the getInstance() method, it is a pretty normal looking class. The constructor initializes our class just as we would expect. We can have pretty standard fields, like &#8220;code&#8221; with normal public getters.</p>
<h3>Is that all there is to it?</h3>
<p>Yup. It is that easy. Almost. Sometimes. There is one more wrinkle. Depending on how this singleton is being used, you may need to account for multiple threads. I am not going to get into that here, as we haven&#8217;t looked at threads yet. Keep in mind that if multiple objects could all call getInstance() at the same time, you may have an issue. Look it up, or wait and see if I get to threads eventually <img src='http://www.cyberward.net/blog/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
<h3>Why use the pattern?</h3>
<ul>
<li>Ensures only one instance of your code with minimal fuss.</li>
<li>The singleton can be assigned.</li>
<li>Uses lazy initialization to save memory.</li>
<li>It is proven. It works. You can try to avoid the pattern, but why bother?</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.cyberward.net/blog/2009/06/intro-to-java-singleton-pattern/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<series:name><![CDATA[Intro to Java]]></series:name>
	</item>
		<item>
		<title>Intro to Java Annotations</title>
		<link>http://www.cyberward.net/blog/2009/05/intro-to-java-annotations/</link>
		<comments>http://www.cyberward.net/blog/2009/05/intro-to-java-annotations/#comments</comments>
		<pubDate>Sat, 30 May 2009 19:13:09 +0000</pubDate>
		<dc:creator>Chris Ward</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[annotations]]></category>
		<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://www.cyberward.net/blog/?p=1225</guid>
		<description><![CDATA[Annotations allow you to attach metadata to a field, class, or method. Metadata is data that describes something else. For example, metadata about a song in mp3 format could be the artists name or the bit rate it was encoded at.  A jpeg image could have metadata that described the image height or the [...]]]></description>
			<content:encoded><![CDATA[<p>Annotations allow you to attach metadata to a field, class, or method. Metadata is data that describes something else. For example, metadata about a song in mp3 format could be the artists name or the bit rate it was encoded at.  A jpeg image could have metadata that described the image height or the number of colors in the image.</p>
<h3>What do they look like?</h3>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1225code39'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p122539"><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code" id="p1225code39"><pre class="java" style="font-family:monospace;">@Override
<span style="color: #000000; font-weight: bold;">public</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a> getName<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #0000ff;">&quot;no name&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>The word after the ‚Äò@‚Äô is the Annotation. It precedes a method or class name. The Override annotation is built into Java. It is used to indicate that a method overrides a parents method. These are used for compiler hinds, for documentation, and to apply meta data.<br />
<span id="more-1225"></span></p>
<h3>Built in Annotations</h3>
<ul>
<li>@Deprecated : used much like the java doc comment</li>
<li>@Override ‚Äì indicates a method overrides a parents method</li>
<li>@SuppressWarnings ‚Äì tells compiler not to indicate warnings</li>
<li>@Documented ‚Äì tells javadoc to document the applied Annotations</li>
<li>@Retention(RetentionPolicy.xxx) ‚Äì indicate to compiler when the Annotation is available</li>
</ul>
<p>Take a look at the Bird.getName() method, and the Animal.getType() method to see a couple of Annotations. Theese classes have been altered slightly here to add some annotations. AnnotationsTest1 shows what you will see in eclipse, or if you compile a deprecated method. AnnotationsTest2 shows how you can use @SupressWarnings.</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1225code40'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p122540"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
</pre></td><td class="code" id="p1225code40"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">interface</span> Animal <span style="color: #009900;">&#123;</span>
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> speak<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> move<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #000000; font-weight: bold;">public</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a> getName<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setName<span style="color: #009900;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a> pName<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #008000; font-style: italic; font-weight: bold;">/**
    * @ deprecated This will not work in the future
    */</span>
   @Deprecated
   <span style="color: #000000; font-weight: bold;">public</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a> getType<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>


<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1225code41'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p122541"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
</pre></td><td class="code" id="p1225code41"><pre class="java" style="font-family:monospace;">@Ratable<span style="color: #009900;">&#40;</span>value<span style="color: #339933;">=</span><span style="color: #cc66cc;">8</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Bird <span style="color: #000000; font-weight: bold;">extends</span> BaseAnimal <span style="color: #009900;">&#123;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> Bird<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">this</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> Bird<span style="color: #009900;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a> pName<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">super</span><span style="color: #009900;">&#40;</span>pName<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Asystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">System</span></a>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Bird created.&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   @Ratable<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">6</span><span style="color: #009900;">&#41;</span>
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> move<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Asystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">System</span></a>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span>getDescription<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot; is flying.&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   @Ratable<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">10</span><span style="color: #009900;">&#41;</span>
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> speak<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Asystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">System</span></a>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span>getDescription<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot; chirps.&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   <span style="color: #008000; font-style: italic; font-weight: bold;">/**
    * Can't use @Override because it is an interface method
    */</span>
   <span style="color: #000000; font-weight: bold;">public</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a> getType<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #0000ff;">&quot;bird&quot;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   @Override
   <span style="color: #000000; font-weight: bold;">public</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a> getName<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #0000ff;">&quot;no name&quot;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>


<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1225code42'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p122542"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
</pre></td><td class="code" id="p1225code42"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> AnnotationsTest1 <span style="color: #009900;">&#123;</span>
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> main<span style="color: #009900;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> args<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
      Fish aFish <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Fish<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      aFish.<span style="color: #006633;">getType</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
      Animal aAnimal <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Fish<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #666666; font-style: italic;">// this line in Eclipse show a strike through on the method</span>
      <span style="color: #666666; font-style: italic;">// when compiling with warnings you would get the error too</span>
      aAnimal.<span style="color: #006633;">getType</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>


<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1225code43'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p122543"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
</pre></td><td class="code" id="p1225code43"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> AnnotationsTest2 <span style="color: #009900;">&#123;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> doWithOutGenerics<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #666666; font-style: italic;">// without generics compiler gives warning about generic type</span>
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Alist+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">List</span></a> aList <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Aarraylist+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">ArrayList</span></a><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      aList.<span style="color: #006633;">clear</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   @SuppressWarnings<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;unchecked&quot;</span><span style="color: #009900;">&#41;</span>
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> doWithAnnotations<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #666666; font-style: italic;">// adding annotation to remove compiler warning</span>
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Alist+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">List</span></a> aList <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Aarraylist+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">ArrayList</span></a><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      aList.<span style="color: #006633;">clear</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> doWithGenerics<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #666666; font-style: italic;">// add type to List and ArrayList</span>
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Alist+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">List</span></a> aList <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Aarraylist+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">ArrayList</span></a><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      aList.<span style="color: #006633;">clear</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<h3>Creating your own Annotations</h3>
<p>If you would like to create your own Annotations, it is not very hard. For example look at the Ratable Annotation.</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1225code44'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p122544"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code" id="p1225code44"><pre class="java" style="font-family:monospace;">@Documented
@Retention<span style="color: #009900;">&#40;</span>RetentionPolicy.<span style="color: #006633;">RUNTIME</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">public</span> @<span style="color: #000000; font-weight: bold;">interface</span> Ratable <span style="color: #009900;">&#123;</span>
&nbsp;
   <span style="color: #000066; font-weight: bold;">int</span> value<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">default</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span>
&nbsp;
   <span style="color: #000066; font-weight: bold;">int</span> rating<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">default</span> <span style="color: #cc66cc;">1</span><span style="color: #339933;">;</span>
&nbsp;
   <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a> why<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">default</span> <span style="color: #0000ff;">&quot;because&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>The class is defined as an @Interface. This makes it an annotation. The strange method definitions that follow are the types of meta data that this annotation can contain. This one can have a value, a rating, and a why. One of the neat things, is that you can provide defaults in the case that someone using your annotation does not provide values for them. So how would you apply this annotation?</p>
<p>Look at the first couple of lines from Fish.</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1225code45'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p122545"><td class="line_numbers"><pre>1
2
</pre></td><td class="code" id="p1225code45"><pre class="java" style="font-family:monospace;">@Ratable<span style="color: #009900;">&#40;</span>rating <span style="color: #339933;">=</span> <span style="color: #cc66cc;">2</span>, why <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;Smells Bad&quot;</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Fish <span style="color: #000000; font-weight: bold;">extends</span> BaseAnimal <span style="color: #009900;">&#123;</span></pre></td></tr></table></div>

<p>The Ratable annotation has been applied to the class Fish with a rating of 2, a value of 0 (default) and a why of ‚ÄúSmells Bad‚Äù.</p>
<h3>Why would you want your own Annotations?</h3>
<p>Why would create your own? If you create an annotation, you can use them with compiler tools to provide information. If you specify a RetentionPolicy of Runtime, then you can use your annotation at Runtime. What good would that be? Think about MP3 files. You can do a search of all your music for all music files that are by a certain author. You can do that with annotations of your classes as well. You can use annotations instead of using instanceof. You can also scan the class path to look for annotations.</p>
<p>Several well know packages and utilities have started to use annotations for configuration. Struts2, JBoss, and hibernate are some you may have heard about. This idea allows you to specify configuration right in the classes themselves instead of in separate XML or properties files.</p>
<p>The Java reflections API provides some help for dealing with these as runtime, but libraries have been created that help with this. One such library is also called ‚Äúreflections‚Äù. AnnotationsTest3 is an example that uses this API.</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1225code46'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p122546"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
</pre></td><td class="code" id="p1225code46"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> AnnotationsTest3 <span style="color: #009900;">&#123;</span>
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> main<span style="color: #009900;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> args<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      AbstractConfiguration configuration <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> AbstractConfiguration<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> 
&nbsp;
      configuration.<span style="color: #006633;">setUrls</span><span style="color: #009900;">&#40;</span>ClasspathHelper.<span style="color: #006633;">getUrlsForCurrentClasspath</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      configuration.<span style="color: #006633;">setScanners</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> ClassAnnotationsScanner<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      configuration.<span style="color: #006633;">setFilter</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> IncludePrefix<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;net.cyberward.tutorial.java.annotations&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
      Reflections reflections <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Reflections<span style="color: #009900;">&#40;</span>configuration<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      Set<span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;</span> annotated <span style="color: #339933;">=</span> reflections.<span style="color: #006633;">getTypesAnnotatedWith</span><span style="color: #009900;">&#40;</span>Ratable.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
      <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">Class</span> aAnnotatedClass <span style="color: #339933;">:</span> annotated<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
         Ratable aRateableAnnotation <span style="color: #339933;">=</span> aAnnotatedClass.<span style="color: #006633;">getAnnotation</span><span style="color: #009900;">&#40;</span>Ratable.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
         <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Asystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">System</span></a>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span>aAnnotatedClass<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
         <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Asystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">System</span></a>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span>aRateableAnnotation<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
         <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Asystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">System</span></a>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;rateing:&quot;</span><span style="color: #339933;">+</span>aRateableAnnotation.<span style="color: #006633;">rating</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
         <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Asystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">System</span></a>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #009900;">&#125;</span>
   <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<h3>More Information:</h3>
<ul>
<li><a href="http://java.sun.com/docs/books/tutorial/java/javaOO/annotations.html">http://java.sun.com/docs/books/tutorial/java/javaOO/annotations.html</a></li>
<li><a href="http://en.wikipedia.org/wiki/Java_annotation">http://en.wikipedia.org/wiki/Java_annotation</a></li>
<li><a href="http://www.javabeat.net/articles/30-annotations-in-java-50-1.html">http://www.javabeat.net/articles/30-annotations-in-java-50-1.html</a></li>
<li><a href="http://code.google.com/p/reflections/">http://code.google.com/p/reflections/</a></li>
</ul>
<p><strong>Note:</strong> If you are using Eclipse and do a ‚ÄúRefactor / Rename‚Ä¶‚Äù of an Annotation, all the places that use the Annotation will be modified too.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cyberward.net/blog/2009/05/intro-to-java-annotations/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<series:name><![CDATA[Intro to Java]]></series:name>
	</item>
		<item>
		<title>Intro to Java Generics</title>
		<link>http://www.cyberward.net/blog/2009/05/intro-to-java-generics/</link>
		<comments>http://www.cyberward.net/blog/2009/05/intro-to-java-generics/#comments</comments>
		<pubDate>Fri, 29 May 2009 14:00:55 +0000</pubDate>
		<dc:creator>Chris Ward</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[generics]]></category>
		<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://www.cyberward.net/blog/?p=1220</guid>
		<description><![CDATA[To me it seems a better word would be Specifics. The use of Generics is applying a specific type to a class that can be used in a generic way. One of the most common generic classes is List. A list allows you to put any type of Object in to it. In fact, you [...]]]></description>
			<content:encoded><![CDATA[<p>To me it seems a better word would be Specifics. The use of Generics is applying a specific type to a class that can be used in a generic way. One of the most common generic classes is List. A list allows you to put any type of Object in to it. In fact, you can put several different types of Objects into a List. But, there is a way to create a specific List type that can only take one type of Object.</p>
<h3>What do they look like?</h3>
<p>Since we are talking about Lists, lets look at what a ArrayList would look like that could only take Strings.</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1220code57'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p122057"><td class="line_numbers"><pre>1
</pre></td><td class="code" id="p1220code57"><pre class="java" style="font-family:monospace;"><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Alist+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">List</span></a> aList <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Aarraylist+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">ArrayList</span></a><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>What goes between the &lt;&gt; is the type that you want to specify for the List. You need to do it in the left side declaration, and on the right side where you are creating the Object.<br />
<span id="more-1220"></span></p>
<h3>Does this work for all classes?</h3>
<p>A class has to be specifically defined for generics. All the collections have been defined this way, and you can create your own classes like this too.</p>
<p>Lets look at the class definition of List:</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1220code58'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p122058"><td class="line_numbers"><pre>1
</pre></td><td class="code" id="p1220code58"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">interface</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Alist+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">List</span></a> <span style="color: #000000; font-weight: bold;">extends</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Acollection+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">Collection</span></a> <span style="color: #009900;">&#123;</span></pre></td></tr></table></div>

<p>Now lets look at methods such as add and get:</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1220code59'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p122059"><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code" id="p1220code59"><pre class="java" style="font-family:monospace;"><span style="color: #000066; font-weight: bold;">boolean</span> add<span style="color: #009900;">&#40;</span>E o<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
E get<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> index<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>In the definition, between the &lt;&gt; List is defined to have a variable E that will contain a class type. (It is always a class type.) This variable can be used anywhere you want to specify this class type. In the case of the add() method, it means that the add method can only accept Objects of the class type E. For the get method, it means that the get method returns an Object of type E.</p>
<h3>How is any of this useful?</h3>
<p>Well, first of all, if you have your compiler set up to compile at a Java 5 level, adding these types removes all the compiler warnings. In Eclipse it will remove all the yellow warnings that are annoying.</p>
<p>More importantly, it allows you to limit the type that you take in with your methods.</p>
<p>GenericsTest1 serves as an example of how you would apply generics to a List.</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1220code60'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p122060"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
</pre></td><td class="code" id="p1220code60"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> GenericsTest1 <span style="color: #009900;">&#123;</span>
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> main<span style="color: #009900;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> args<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #666666; font-style: italic;">// Create a List without specifying type parameters</span>
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Alist+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">List</span></a> aList1 <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Aarraylist+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">ArrayList</span></a><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      aList1.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Bird<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      aList1.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Fish<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      aList1.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Mammal<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #666666; font-style: italic;">// Does compiler complain? Does it work at runtime?</span>
      <span style="color: #666666; font-style: italic;">//aList1.add(new Object());</span>
&nbsp;
      <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Aiterator+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">Iterator</span></a> iterator <span style="color: #339933;">=</span> aList1.<span style="color: #006633;">iterator</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> iterator.<span style="color: #006633;">hasNext</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
         <span style="color: #666666; font-style: italic;">//notice the need for a cast</span>
         Animal aAnimal <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>Animal<span style="color: #009900;">&#41;</span> iterator.<span style="color: #006633;">next</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
         aAnimal.<span style="color: #006633;">move</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #009900;">&#125;</span>
&nbsp;
      <span style="color: #666666; font-style: italic;">// Create a List and specify that only an Animal can be used.</span>
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Alist+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">List</span></a> aList2 <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Aarraylist+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">ArrayList</span></a><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      aList2.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Bird<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      aList2.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Fish<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      aList2.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Mammal<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #666666; font-style: italic;">// Does compiler complain? Does it work at runtime?</span>
      <span style="color: #666666; font-style: italic;">//aList2.add(new Object());</span>
&nbsp;
      <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Aiterator+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">Iterator</span></a> iterator <span style="color: #339933;">=</span> aList2.<span style="color: #006633;">iterator</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> iterator.<span style="color: #006633;">hasNext</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
         <span style="color: #666666; font-style: italic;">// notice no casting</span>
         Animal aAnimal <span style="color: #339933;">=</span> iterator.<span style="color: #006633;">next</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
         aAnimal.<span style="color: #006633;">move</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #009900;">&#125;</span>
   <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>GenericsTest2 shows a similar example, but using a Map.</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1220code61'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p122061"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
</pre></td><td class="code" id="p1220code61"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> GenericsTest2 <span style="color: #009900;">&#123;</span>
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> main<span style="color: #009900;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> args<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Ainteger+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">Integer</span></a> aIntegerKey <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Ainteger+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">Integer</span></a><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">10</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
      <span style="color: #666666; font-style: italic;">// Create a Map without specifying type parameters</span>
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Amap+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">Map</span></a> aMap1 <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Ahashmap+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">HashMap</span></a><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      aMap1.<span style="color: #006633;">put</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;bird&quot;</span>, <span style="color: #000000; font-weight: bold;">new</span> Bird<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      aMap1.<span style="color: #006633;">put</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;fish&quot;</span>, <span style="color: #000000; font-weight: bold;">new</span> Fish<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #666666; font-style: italic;">// Notice that there is no restriction on the key type</span>
      aMap1.<span style="color: #006633;">put</span><span style="color: #009900;">&#40;</span>aIntegerKey, <span style="color: #000000; font-weight: bold;">new</span> Mammal<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
      Animal aBird <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>Animal<span style="color: #009900;">&#41;</span> aMap1.<span style="color: #006633;">get</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;bird&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      aBird.<span style="color: #006633;">move</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
      Animal aFish <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>Animal<span style="color: #009900;">&#41;</span> aMap1.<span style="color: #006633;">get</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;fish&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      aFish.<span style="color: #006633;">move</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
      Animal aMammal <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>Animal<span style="color: #009900;">&#41;</span> aMap1.<span style="color: #006633;">get</span><span style="color: #009900;">&#40;</span>aIntegerKey<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      aMammal.<span style="color: #006633;">move</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
      <span style="color: #666666; font-style: italic;">// Create a Map an specify that only a String key and an Animal value</span>
      <span style="color: #666666; font-style: italic;">// can be used in the map.</span>
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Amap+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">Map</span></a> aMap2 <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Ahashmap+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">HashMap</span></a><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      aMap2.<span style="color: #006633;">put</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;bird&quot;</span>, <span style="color: #000000; font-weight: bold;">new</span> Bird<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      aMap2.<span style="color: #006633;">put</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;fish&quot;</span>, <span style="color: #000000; font-weight: bold;">new</span> Fish<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
      <span style="color: #666666; font-style: italic;">// What happens when this is uncommented</span>
      <span style="color: #666666; font-style: italic;">//aMap2.put(aIntegerKey, new Mammal());</span>
&nbsp;
      Animal aBird2 <span style="color: #339933;">=</span> aMap2.<span style="color: #006633;">get</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;bird&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      aBird2.<span style="color: #006633;">move</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
      Animal aFish2 <span style="color: #339933;">=</span> aMap2.<span style="color: #006633;">get</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;fish&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      aFish2.<span style="color: #006633;">move</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
      <span style="color: #666666; font-style: italic;">//What happens when this is uncommented. Compiler? Run time? Why?</span>
      <span style="color: #666666; font-style: italic;">//Animal aMammal2 = aMap2.get(aIntegerKey);</span>
      <span style="color: #666666; font-style: italic;">//aMammal2.move();</span>
   <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Now lets rewrite a couple of things to use generics.</p>
<p>Look at the CollectionUtilities.printAnimalList() method from the ‚ÄúIntro to Java Collections‚Äù lesson.</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1220code62'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p122062"><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code" id="p1220code62"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> printAnimalList<span style="color: #009900;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Alist+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">List</span></a> pAnimalList<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
   <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Aiterator+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">Iterator</span></a> iterator <span style="color: #339933;">=</span> pAnimalList.<span style="color: #006633;">iterator</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> iterator.<span style="color: #006633;">hasNext</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #666666; font-style: italic;">// notice the need for a cast</span>
      Animal aAnimal <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>Animal<span style="color: #009900;">&#41;</span> iterator.<span style="color: #006633;">next</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Asystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">System</span></a>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span>aAnimal.<span style="color: #006633;">getName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;:&quot;</span> <span style="color: #339933;">+</span> aAnimal.<span style="color: #006633;">getType</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>You can‚Äôt get much more un type safe than this. We define the method to only take in a List. But in the code we expect to only have Animals. We also have to cast to an Animal because when the List is created we don‚Äôt define a specific type, so the list can contain any type of Object.</p>
<p>Lets rewrite this method using generics.</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1220code63'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p122063"><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code" id="p1220code63"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> printAnimalList<span style="color: #009900;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Alist+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">List</span></a> pAnimalList<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
   <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Aiterator+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">Iterator</span></a> iterator <span style="color: #339933;">=</span> pAnimalList.<span style="color: #006633;">iterator</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> iterator.<span style="color: #006633;">hasNext</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #666666; font-style: italic;">// notice no casting</span>
      Animal aAnimal <span style="color: #339933;">=</span> iterator.<span style="color: #006633;">next</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Asystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">System</span></a>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span>aAnimal.<span style="color: #006633;">getName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;:&quot;</span> <span style="color: #339933;">+</span> aAnimal.<span style="color: #006633;">getType</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Our method definition has determined that only Lists that contain Animal types are allowed. If someone tried to use this method with a List of Strings, the compiler would not let it happen. Also notice that we no longer need to cast from this Iterator. That is because the .iterator() method in List returns a  Iterator, and Iterator doesn‚Äôt return just an Object, but one of the Animal type.</p>
<p>Even better, lets use a new Java 5 looping structure called a ‚Äúfor each‚Äù loop. This works for any class that implements the Iterable interface (like List).</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1220code64'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p122064"><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code" id="p1220code64"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> printAnimalList<span style="color: #009900;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Alist+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">List</span></a> pAnimalList<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
   <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span>Animal aAnimal <span style="color: #339933;">:</span> pAnimalList<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Asystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">System</span></a>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span>aAnimal.<span style="color: #006633;">getName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;:&quot;</span> <span style="color: #339933;">+</span> aAnimal.<span style="color: #006633;">getType</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Now lets look at Cage. Cage is a version of a cage that allows you to specify what type of animal the cage contains using generics. See GenericsTest3. This is not quite the same as BirdCage, it is not a singleton, but BirdCage could also be rewritten so that it could be a cage for any animal, not just birds. Try to rewrite it using this Cage as an example.</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1220code65'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p122065"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
</pre></td><td class="code" id="p1220code65"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Cage <span style="color: #009900;">&#123;</span>
   <span style="color: #666666; font-style: italic;">// We can then use T to define our list class type</span>
   <span style="color: #000000; font-weight: bold;">private</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Alist+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">List</span></a> animalList<span style="color: #339933;">;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> Cage<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #666666; font-style: italic;">// When we create the list we must tell it a type too.</span>
      animalList <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Aarraylist+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">ArrayList</span></a><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   <span style="color: #666666; font-style: italic;">// We can even specify in a method signature that only objects of type T are</span>
   <span style="color: #666666; font-style: italic;">// allowed to be here. Not just any Animal, but just of class type T.</span>
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> insertAnimal<span style="color: #009900;">&#40;</span>T pAnimal<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      animalList.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span>pAnimal<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Asystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">System</span></a>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span>pAnimal.<span style="color: #006633;">getName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot; &quot;</span> <span style="color: #339933;">+</span> pAnimal.<span style="color: #006633;">getType</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot; is in the cage.&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   <span style="color: #666666; font-style: italic;">// When we return our list, it will be a list that only contains class type</span>
   <span style="color: #666666; font-style: italic;">// T, and you won't need to cast individual elements from the list.</span>
   <span style="color: #000000; font-weight: bold;">public</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Alist+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">List</span></a> getAnimals<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">return</span> animalList<span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>


<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1220code66'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p122066"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
</pre></td><td class="code" id="p1220code66"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> GenericsTest3 <span style="color: #009900;">&#123;</span>
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> main<span style="color: #009900;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> args<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #666666; font-style: italic;">// Without specifying type parameters the compiler gives us all kinds of warnings.</span>
      Cage aCage <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Cage<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      aCage.<span style="color: #006633;">insertAnimal</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Bird<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #666666; font-style: italic;">// Notice that because we didn't specify a type when we created the</span>
      <span style="color: #666666; font-style: italic;">// Cage, we can actually add a fish.</span>
      aCage.<span style="color: #006633;">insertAnimal</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Fish<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
      <span style="color: #666666; font-style: italic;">// Lets add parameters.</span>
      Cage aBirdCage <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Cage<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      aBirdCage.<span style="color: #006633;">insertAnimal</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Bird<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      aBirdCage.<span style="color: #006633;">insertAnimal</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Bird<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #666666; font-style: italic;">// What happens when this is uncommented</span>
      <span style="color: #666666; font-style: italic;">// aBirdCage.insertAnimal(new Fish());</span>
&nbsp;
      <span style="color: #666666; font-style: italic;">// You can get back a non parameterized list, and it is functional, but</span>
      <span style="color: #666666; font-style: italic;">// you get a warning from the compiler.</span>
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Alist+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">List</span></a> aList2 <span style="color: #339933;">=</span> aBirdCage.<span style="color: #006633;">getAnimals</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Asystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">System</span></a>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span>aList2.<span style="color: #006633;">size</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
      <span style="color: #666666; font-style: italic;">// Add the type parameter to list to make the compiler happy.</span>
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Alist+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">List</span></a> aBirdList <span style="color: #339933;">=</span> aBirdCage.<span style="color: #006633;">getAnimals</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Asystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">System</span></a>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span>aBirdList.<span style="color: #006633;">size</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<h3>Letter Conventions</h3>
<p>There is no restriction on what letters you can use in your class definitions and method signatures. In fact, instead of ‚ÄúT‚Äù you could use ‚ÄúQQ‚Äù or ‚ÄúType‚Äù. It seems that the Java authors have settled on using just one letter, and they themselves have been fairly consistent about the letters they use.</p>
<p>In the collections packages they usually use ‚ÄúE‚Äù for element. So when you look at the interface for List, you will see .</p>
<p>If you look at the Map interface, you will see  for Key and Value.</p>
<p>Also, other classes that take in a class type usually use the letter ‚ÄúT‚Äù for type.</p>
<h3>More Information:</h3>
<ul>
<li><a href="http://java.sun.com/docs/books/tutorial/java/generics/index.html">http://java.sun.com/docs/books/tutorial/java/generics/index.html</a></li>
<li><a href="http://java.sun.com/j2se/1.5.0/docs/guide/language/generics.html">http://java.sun.com/j2se/1.5.0/docs/guide/language/generics.html</a></li>
<li><a href="http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf">http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf (pdf)</a></li>
<li><a href="http://en.wikipedia.org/wiki/Generics_in_Java">http://en.wikipedia.org/wiki/Generics_in_Java</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.cyberward.net/blog/2009/05/intro-to-java-generics/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<series:name><![CDATA[Intro to Java]]></series:name>
	</item>
		<item>
		<title>Intro to Java Collections</title>
		<link>http://www.cyberward.net/blog/2009/05/intro-to-java-collections/</link>
		<comments>http://www.cyberward.net/blog/2009/05/intro-to-java-collections/#comments</comments>
		<pubDate>Thu, 28 May 2009 16:09:13 +0000</pubDate>
		<dc:creator>Chris Ward</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[collections]]></category>
		<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://www.cyberward.net/blog/?p=1212</guid>
		<description><![CDATA[I don&#8217;t want to get too deep into every little thing in the collections classes here. In fact, you already know a fair bit about them, because we have used them with some of our Animal class examples. This is more an overview of some of the basic Collections classes.
What do they look like?
There are [...]]]></description>
			<content:encoded><![CDATA[<p>I don&#8217;t want to get too deep into every little thing in the collections classes here. In fact, you already know a fair bit about them, because we have used them with some of our Animal class examples. This is more an overview of some of the basic Collections classes.</p>
<h3>What do they look like?</h3>
<p>There are three main types of collections: Lists, Maps, and Sets. Technically you could try to argue that Map doesn&#8217;t extend Collection, so therefore it is not a Collection, but I think of it as part of the group.<br />
They are used for groups of objects, or exactly as its name would imply, collections of objects.</p>
<h3>List</h3>
<p>A List is just that, a list of objects. The List interface provides a way to add, remove and get objects from a list. It however is just an interface. ArrayList is one of the more popular concrete collections that implements the List interface. Each implementation of the List interface may behave slightly different, but once you understand how a List works, you have a good start on understanding any List.<br />
<span id="more-1212"></span><br />
An ArrayList can be thought of in some ways like an Array, but there are some differences. One of the biggest is that you can keep adding or removing from an ArrayList (or any List) without needing to have defined it in a constructor.</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1212code68'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p121268"><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code" id="p1212code68"><pre class="java" style="font-family:monospace;"><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Alist+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">List</span></a> aList <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Aarraylist+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">ArrayList</span></a><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> aArray <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">5</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>On the first line we created a generic list that can hold ANY type of object, and of any amount of them. On the second line, we created an Array that always has a size of 5, and can only hold Strings. (The type limitation can be seen as a positive or a negative, and we will look at how we can do similar things with Lists when we get to Generics in a different lesson.) </p>
<p>Some of the typical methods of List you will use are :</p>
<p>‚Ä¢ add(Object o) : to add an element to the end of the list<br />
‚Ä¢ add(int index, Object o) : to add an object at a particular index<br />
‚Ä¢ boolean remove(Object o) : remove the specific Object<br />
‚Ä¢ remove(int index) : remove the Object at a particular index<br />
‚Ä¢ boolean contains(Object o) : if an object exists in the list<br />
‚Ä¢ int indexOf(Object o) : position of an index in the list<br />
‚Ä¢ Object get(int index) : return the Object from a particular index<br />
‚Ä¢ Iterator iterator() : return an Iterator for the list<br />
‚Ä¢ size() : number of elements in the list<br />
‚Ä¢ Object[] toArray(Object[] o) : return an Array of type o</p>
<pre lang="Java" name="CollectionsTest1.java" colla="-">
public class CollectionsTest1 {
   public static void main(String[] args) {
      // List is just an interface. We need to create something that
      // implements List, and ArrayList is one such Class that is pretty
      // common, but not the only one.
      List aList1 = new ArrayList();
      aList1.add(new Bird("Tweety"));
      aList1.add(new Fish("Swimmy"));
      aList1.add(new Mammal());
      // Does compiler complain? Does it work at runtime?
      // aList1.add(new String("Johnny"));

      // To prove that our List is a Collection, we have a static method that
      // will print out any item from a Collection
      CollectionUtilities.printAnimalList(aList1);
   }
}
</pre>
<pre lang="Java" name="CollectionUtilities.java" colla="-">
public class CollectionUtilities {

   /**
    * Any object that extends Collection can be printed here. It works because
    * you can get an iterator from a collection object.
    *
    * @param pCollection
    */
   public static void printList(Collection pCollection) {

      for (Iterator iterator = pCollection.iterator(); iterator.hasNext();) {
         Object aObject = iterator.next();
         System.out.println(aObject);
      }
   }

   /**
    * Note that for now, we are only specifying a list, there is nothing to
    * stop you from passing in a list of any type of object. See the generics
    * lesson for more info.
    *
    * @param pAnimalList
    */
   public static void printAnimalList(List pAnimalList) {
      for (Iterator iterator = pAnimalList.iterator(); iterator.hasNext();) {
         // notice the need for a cast
         Animal aAnimal = (Animal) iterator.next();
         System.out.println(aAnimal.getName() + ":" + aAnimal.getType());
      }
   }

   /**
    * Sorts a List of elements of type Animal useing the AnimalComparator
    *
    * @param pAnimalList
    */
   public static void sortAnimals(List pAnimalList) {
      Collections.sort(pAnimalList, new AnimalComparator());
   }

   /**
    * Figured if we had a comparator, we should use it on an array too.
    *
    * @param pAnimalArray
    */
   public static void sortAnimals(Animal[] pAnimalArray) {
      Arrays.sort(pAnimalArray, new AnimalComparator());
   }

   /**
    * Shows how we can take in a list and return a set
    *
    * @param pAnimalList
    * @return
    */
   public static Set findBirds(List pAnimalList) {
      Set aBirdSet = new HashSet();
      for (Iterator iterator = pAnimalList.iterator(); iterator.hasNext();) {
         Animal aAnimal = (Animal) iterator.next();
         if ( aAnimal instanceof Bird ) {
            aBirdSet.add(aAnimal);
         }
      }
      return aBirdSet;
   }
}
</pre>
<p>CollectionsTest1.java is a very basic class that uses an ArrayList. One of powerful features of Java is the use of Interfaces. Using them, we can create methods that know enough to get the job done, but little enough that they are still generic. That is the idea behind CollectionUtilities. The printList method can print anything that is a Collection. The printAnimalList can print more details as long as the item is a List of Animals.</p>
<pre lang="Java" name="CollectionsTest2.java" colla="-">
public class CollectionsTest2 {
   public static void main(String[] args) {
      List aList1 = new ArrayList();
      aList1.add(new Bird("Birdy"));
      // size() method will print number of elements in the list
      System.out.println(aList1.size());
      // clear() method will remove all elements from list
      aList1.clear();
      System.out.println(aList1.size());

      Bird aTweety = new Bird("Tweety");
      aList1.add(aTweety);
      aList1.add(new Fish("Swimmy"));
      aList1.add(new Mammal());

      // contains() method is used to check the list for a particular object
      if (aList1.contains(aTweety)) {
         System.out.println("found tweety");
      } else {
         System.out.println("tweety has flown the coop");
      }
      // remember, this is object equals
      if (aList1.contains(new Fish("Swimmy"))) {
         System.out.println("found swimmy");
      } else {
         System.out.println("swimmy has left the building");
      }

      // get() method to retrieve an object from the list
      Animal aMammal1 = (Animal) aList1.get(2);
      System.out.println("aMammal1(index 2):" + aMammal1.getName());

      // This object is "live". The list only contains pointers to the real
      // objects. Change an object from the list...
      aMammal1.setName("Rover");

      // and the object in the list is changed.
      Animal aMammal2 = (Animal) aList1.get(2);
      System.out.println("aMammal2(index 2):" + aMammal2.getName());
   }
}
</pre>
<p>CollectionsTest2 shows some of the other methods that are commonly used with Lists.</p>
<p>Another interesting thing that is often done with Lists, is to sort them. You can sort Objects in anyway imaginable that makes sense to your for your particular object. One way to do this is to create a reusable class called a Comparator. AnimalComparator is a Comparator that can be used to sort based on first the type, then the name of the Animal. CollectionsTest3 shows how to use this comparator to sort both a List and an Array. This class also shows how you can take a List and turn it into an Array.</p>
<pre lang="Java" name="AnimalComparator.java" colla="-">
/**
 * This Comparator can be used to sort animals. A null animal is < an actual
 * animal. The order is alphabetical on type, then alphabetical on name.
 *
 * Note: not null safe on type and name. If running against VERY large lists you
 * may want to try to avoid creating all the Strings for type and name.
 *
 * @author Chris Ward <veggie2u@cyberward.net>
 */
public class AnimalComparator implements Comparator {
   public int compare(Object pAnimal1, Object pAnimal2) {
      if (pAnimal1 == null &#038;&#038; pAnimal2 == null) {
         return 0; // equal
      }
      if (pAnimal1 == null) {
         return -1; // pAnimal1 < pAnimal2
      }
      if (pAnimal2 == null) {
         return 1; // pAnimal 1 > pAnimal2
      }

      String aType1 = ((Animal) pAnimal1).getType();
      String aType2 = ((Animal) pAnimal2).getType();

      int aTypeCompare = aType1.compareTo(aType2);
      // If different, we don't need to compare anymore
      if (aTypeCompare != 0) {
         return aTypeCompare;
      }

      String aName1 = ((Animal) pAnimal1).getName();
      String aName2 = ((Animal) pAnimal2).getName();
      return aName1.compareTo(aName2);
   }
}
</pre>
<pre lang="Java" name="CollectionsTest3.java" colla="-">
public class CollectionsTest3 {
   public static void main(String[] args) {
      List aList1 = new ArrayList();
      aList1.add(new Bird("Tweety"));
      aList1.add(new Fish("Swimmy"));
      aList1.add(new Mammal());
      aList1.add(new Bird("Robby Robbin"));
      aList1.add(new Mammal("Zeke"));

      System.out.println();
      CollectionUtilities.printAnimalList(aList1);

      // sort using a comparator
      CollectionUtilities.sortAnimals(aList1);

      System.out.println();
      CollectionUtilities.printAnimalList(aList1);

      System.out.println();
      List aList2 = new ArrayList();
      aList2.add(new Bird("Tweety"));
      aList2.add(new Fish("Swimmy"));
      aList2.add(new Mammal());
      aList2.add(new Bird("Robby Robbin"));
      aList2.add(new Mammal("Zeke"));

      // A List can convert to an Array
      Animal[] aAnimalArray = (Animal[]) aList2.toArray(new Animal[0]);

      // You can sort an array with the same comparator
      CollectionUtilities.sortAnimals(aAnimalArray);

      System.out.println();
      for (int i = 0; i < aAnimalArray.length; i++) {
         System.out.println(aAnimalArray[i].getName());
      }
   }
}
</pre>
<h3>Map</h3>
<p>A Map is like a look up table, or index table. For every object that goes into the Map, you have to give an index to where it is. A List can know where each object is by a numeric index, but if you removed the first object, you would no longer know the index of any of the Objects in your list! By using a Map, you can use any type of index you wish. You can use Integers, Strings, or any Object you can come up with. As with List, Map is just an Interface. We will use the HashMap in our examples.</p>
<p>CollectionsTest4 shows how to use a Map and how the concept of keys works. </p>
<pre lang="Java" name="CollectionsTest4.java" colla="-">
public class CollectionsTest4 {
   public static void main(String[] args) {
      Integer aIntegerKey = new Integer(10);

      Map aMap1 = new HashMap();
      aMap1.put("bird", new Bird());
      aMap1.put("fish", new Fish());
      // Notice that there is no restriction on the key type
      aMap1.put(aIntegerKey, new Mammal());

      // Note: Map doesn't actually implement the Collection interface
      // CollectionUtilities.printList(aMap1);

      // A map stores Objects, must cast to Animal
      Animal aBird = (Animal) aMap1.get("bird");
      System.out.println(aBird);

      // Non Strings work as keys just fine
      Mammal aMammal = (Mammal) aMap1.get(aIntegerKey);
      System.out.println(aMammal);
   }
}
</pre>
<p>Some of the more common methods of a Map are:</p>
<p>‚Ä¢ Object put(Object key, Object value)<br />
‚Ä¢ Object get(Object key)<br />
‚Ä¢ boolean containsKey(Object key) : check to see if a particular key exists in the Map<br />
‚Ä¢ boolean containsValue(Object value) : check to see if a particular value exits in the Map<br />
‚Ä¢ Object remove(Object key) : remove the entry that has the particular key<br />
‚Ä¢ int size()</p>
<p>If you get a lot of Birds in a cage, it is tough to remember what bird is inside, so let's use a HashMap to create a cache of Bird objects. BirdCage will use the bird's name as the key, and the actual Bird object as the value. See CollectionsTest5 to see this implemented.</p>
<pre lang="Java" name="BirdCage.java" colla="-">
/**
 * Using a HashMap to implement a type of cache. We use the name of our Bird's
 * as the key. The Bird its self is the value. If the bird does not exist in our
 * cache, we add it. It it is there, we return the one we found.
 *
 * @author Chris Ward <veggie2u@cyberward.net>
 */
public class BirdCage {

   private static BirdCage birdCage;
   private Map birdCache;

   /**
    * The BirdCage is a singleton. We have decided that there will be only one
    * bird cage in per java machine.
    */
   private BirdCage() {
      birdCache = new HashMap();
      System.out.println("Creating a BirdCage. There can be only one bird with a given name.");
   }

   public static BirdCage getInstance() {
      if (birdCage == null) {
         birdCage = new BirdCage();
      }
      return birdCage;
   }

   public Bird checkCage(String pName) {
      if (birdCage == null) {
         getInstance();
      }

      if (!birdCache.containsKey(pName)) {
         System.out.println(pName + " not found... adding.");
         Bird aBird = new Bird(pName);
         birdCache.put(pName, aBird);
         return aBird;
      }
      System.out.println("The name " + pName + " was found");
      System.out.println("Returning original " + pName);
      return (Bird) birdCache.get(pName);
   }

   public int getSize() {
      return birdCache.size();
   }

   public boolean isInCage(String pName) {
      return birdCache.containsKey(pName);
   }
}
</pre>
<pre lang="Java" name="CollectionsTest5.java" colla="-">
public class CollectionsTest5 {
   public static void main(String[] args) {
      BirdCage aCage = BirdCage.getInstance();

      Bird aTweety1 = aCage.checkCage("Tweety");
      Bird aRobby = aCage.checkCage("Robby Robbin");
      //will Tweety be added twice?
      Bird aTweety2 = aCage.checkCage("Tweety");
      Bird aSam = aCage.checkCage("Sam");

      //What will be the size?
      System.out.println("size:" + aCage.getSize());

      //Will these two birds be equal?
      System.out.println("Tweety1 == Tweety2 : " + aTweety1.equals(aTweety2));
      System.out.println("Frank is in cage? " + aCage.isInCage("Frank"));
      System.out.println("Sam is in cage? " + aCage.isInCage("Sam"));
   }
}
</pre>
<h3>Set</h3>
<p>A set is like a partial List. They are often returned from a collection when you have asked for some subset of the whole. For example, if we had a big list of Animals, and we wanted to find out what of these Animals were Birds, we could get a Set back. The methods of Set are much like the List, but with a Set, no two elements are equal within a Set. There are no duplicates.</p>
<p>As an example, take a look at the CollectionsTest6 class. This creates a list, then asks a method from the CollectionUtilities to return a Set of just the Birds.</p>
<pre lang="Java" name="CollectionsTest6.java" colla="-">
public class CollectionsTest6 {
   public static void main(String[] args) {
      List aAnimalList = new ArrayList();
      aAnimalList.add(new Bird("Tweety"));
      aAnimalList.add(new Fish());
      aAnimalList.add(new Mammal());
      aAnimalList.add(new Bird());
      aAnimalList.add(new Bird("Sam"));

      Set aBirdSet = CollectionUtilities.findBirds(aAnimalList);
      CollectionUtilities.printList(aBirdSet);
   }
}
</pre>
<h3>More Information</h3>
<p>Java collections trail: <a href="http://java.sun.com/docs/books/tutorial/collections/index.html">http://java.sun.com/docs/books/tutorial/collections/index.html</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.cyberward.net/blog/2009/05/intro-to-java-collections/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<series:name><![CDATA[Intro to Java]]></series:name>
	</item>
		<item>
		<title>Intro to Java Adapter Pattern</title>
		<link>http://www.cyberward.net/blog/2009/04/intro-to-java-adapter-pattern/</link>
		<comments>http://www.cyberward.net/blog/2009/04/intro-to-java-adapter-pattern/#comments</comments>
		<pubDate>Thu, 23 Apr 2009 20:00:47 +0000</pubDate>
		<dc:creator>Chris Ward</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[adapter]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[patterns]]></category>

		<guid isPermaLink="false">http://www.cyberward.net/blog/?p=1074</guid>
		<description><![CDATA[In the last lesson we looked at patterns in general and why we might want to use them. So here is our first pattern. We are well on our way to creating a common language with which to talk design.
One of the reasons I picked this pattern to start with, is that it is very [...]]]></description>
			<content:encoded><![CDATA[