Saturday, October 31, 2009

Section 6.1. Object Instances










6.1. Object Instances








To draw an object diagram, the first thing you need to add are the actual objects themselves. Object notation is actually very simple if you're already familiar with class notation; an object is shown with a rectangle, just like a class, but to show that this is an instance of a class rather than the class itself, the title is underlined, as shown in Figure 6-2.



Figure 6-2. You show an instantiated object by using a rectangle but with the name of the objectits identifierunderlined



The enTRy object in Figure 6-2 has only an identity with which the object can be referred tothe enTRy name. However, if you happen to also know the class that this object instantiates, then you can also add the class name to the object name, as shown in Figure 6-3.



Figure 6-3. The entry object is an instance of the BlogEntry class from Chapter 4



There is one final type of object that you might want to use on your object diagramsthe anonymous object, shown in Figure 6-4.



Figure 6-4. The class of this object is ActionListener, but the name or identity is not specified; this object also shows the single actionPerformed(...) method that is required by the ActionListener interface



Anonymous objects are typically useful when the name of the object is not important within the context that it is being used. For example, it is a common programming idiom when you create an event handler in Java using an anonymous object because you don't care what the name of the object is, just that it is registered with the appropriate event source, as shown in Example 6-1.


Example 8-1. Using an anonymous object in Java code to register an ActionListener




with a JButton
public void initialiseUI( ) {
//... Other method implementation code ...
 
JButton button = new Jbutton("Submit");
button.addActionListener(new ActionListener{
public void actionPerformed(ActionEvent e)
{
System.out.println("The button was pressed so it's time to do something ...");
}
});

 
//... Other method implementation code ...
}




You might also notice in Example 6-1 that the anonymous object is implementing an interface as it is declared. As the anonymous object is instantiated, it implements the actionPerformed(...) method that is required by the ActionListener interface.













No comments: