1. Trang chủ
  2. » Công Nghệ Thông Tin

Java All-in-One Desk Reference For Dummies phần 5 docx

89 196 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Declaring Inner Classes 330 Understanding inner classes At the surface, an inner class is simply a class that’s contained inside another class. However, there’s more to it than that. Here are some key points about inner classes: ✦ An inner class automatically has access to all the fields and methods of the outer class — even private fields and methods. Thus, an inner class has more access to its outer class than a subclass has to its superclass. (A subclass can access public and protected members of its superclass, but not private members.) ✦ An inner class carries with it a reference to the current instance of the outer class that enables it to access instance data for the outer class. ✦ Because of the outer class instance reference, you can’t create or refer to an inner class from a static method of the outer class. You can, how- ever, create a static inner class, as I describe in the section “Using Static Inner Classes” later in this chapter. ✦ One of the main reasons for creating an inner class is to create a class that’s only of interest to the outer class. As a result, you usually declare inner classes to be private so other classes can’t access them. ✦ Occasionally, code in an inner class needs to refer to the instance of its outer class. To do that, you list the name of the outer class followed by the dot operator and this. For example, if the outer class is named MyOuterClass, you would use MyOuterClass.this to refer to the instance of the outer class. An example Book III, Chapter 5 introduces an application that uses the Timer class in the Swing package ( javax.swing.Timer) that displays the lines Tick and Tock on the console at a one second interval. It uses a class named Ticker that implements the ActionListener interface to handle the Timer object’s clock events. In this chapter, you see a total of three different versions of this application. You may want to quickly review Book III, Chapter 5 if you’re unclear on how this application uses the Timer class to display the Tick and Tock messages, or why the JOptionPane dialog box is required. Listing 7-1 shows a version of this application that implements the Ticker class as an inner class. 25_58961X bk03ch07.qxd 3/29/05 3:44 PM Page 330 Book III Chapter 7 Using Inner Classes Declaring Inner Classes 331 LISTING 7-1: TICK TOCK WITH AN INNER CLASS import java.awt.event.*; import javax.swing.*; public class TickTockInner { private String tickMessage = “Tick ”; ➞ 6 private String tockMessage = “Tock ”; ➞ 7 public static void main(String[] args) { TickTockInner t = new TickTockInner(); ➞ 11 t.go(); ➞ 12 } private void go() ➞ 15 { // create a timer that calls the Ticker class // at one second intervals Timer t = new Timer(1000, new Ticker()); ➞ 19 t.start(); // display a message box to prevent the // program from ending immediately JOptionPane.showMessageDialog(null, ➞ 24 “Click OK to exit program”); System.exit(0); ➞ 26 } class Ticker implements ActionListener ➞ 29 { private boolean tick = true; public void actionPerformed(ActionEvent event) ➞ 33 { if (tick) { System.out.println(tickMessage); ➞ 37 } else { System.out.println(tockMessage); ➞ 41 } tick = !tick; } } } 25_58961X bk03ch07.qxd 3/29/05 3:44 PM Page 331 Declaring Inner Classes 332 The following paragraphs describe some of the highlights of this program: ➞ 6 The String variables named tickMessage and tockMessage (line 7) contain the messages to be printed on the console. Note that these variables are defined as fields of the outer class. As you’ll see, the inner class Ticker is able to directly access these fields. ➞ 11 Because an inner class can only be used by an instantiated object, you can’t use it directly from the static main method. As a result, the main method in this program simply creates an instance of the appli- cation class ( TickTockInner). ➞ 12 This line executes the go method of the new instance of the TickTockInner class. The technique used in lines 11 and 12 is a fairly common programming technique that lets an application quickly get out of a static context and into an object-oriented mode. ➞ 15 The go method, called from line 12. ➞ 19 This line creates an instance of the Timer class with the timer inter- val set to 1,000 milliseconds (1 second) and the ActionListener set to a new instance of the inner class named Ticker. ➞ 24 Here, the JOptionPane class is used to display a dialog box. This dialog box is necessary to give the timer a chance to run. The appli- cation ends when the user clicks OK. ➞ 26 This line calls the exit method of the System class, which immedi- ately shuts down the Java Virtual Machine. This method call isn’t strictly required here, but if you leave it out, the timer continues to The Observer Pattern Event listeners in Java are part of a Java model called the Delegation Event Model. The Delega- tion Event Model is an implementation of a more general design pattern called the Observer pat- tern. This pattern is useful when you need to create objects that interact with each other when a change in the status of one of the objects occurs. The object whose changes are being monitored is called the observable object, and the object that monitors those changes is called the observer object. The observer object registers itself with the observable object, which then notifies the observer object when its status changes. You discover more about how Java implements this pattern for event handling in Book VI. But if you’re interested, you may want to investigate the Observer and Observable inter- faces that are a part of the Java API. They pro- vide a standard way to create simple implementations of the Observer pattern. 25_58961X bk03ch07.qxd 3/29/05 3:44 PM Page 332 Book III Chapter 7 Using Inner Classes Using Static Inner Classes 333 run for a few seconds after you click OK before the JVM figures out that it should kill the timer. ➞ 29 This line is the declaration for the inner class named Ticker. Note that this class implements the ActionListener interface. ➞ 33 The actionPerformed method is called by the Timer object every 1,000 milliseconds. ➞ 37 In this line and in line 41, the inner class directly accesses a field of the outer class. Using Static Inner Classes A static inner class is similar to an inner class, but doesn’t require an instance of the outer class. Its basic form is the following: class outerClassName { private static class innerClassName { // body of inner class } } Like a static method, a static inner class can’t access any non-static fields or methods in its outer class. It can, however, access static fields or methods. Listing 7-2 shows a version of the Tick Tock application that uses a static inner class rather than a regular inner class. LISTING 7-2: TICK TOCK WITH A STATIC INNER CLASS import java.awt.event.*; import javax.swing.*; public class TickTockStatic { private static String tickMessage = “Tick ”; ➞ 6 private static String tockMessage = “Tock ”; ➞ 7 public static void main(String[] args) { TickTockStatic t = new TickTockStatic(); t.go(); } continued 25_58961X bk03ch07.qxd 3/29/05 3:44 PM Page 333 Using Anonymous Inner Classes 334 LISTING 7-2 (CONTINUED) private void go() { // create a timer that calls the Ticker class // at one second intervals Timer t = new Timer(1000, new Ticker()); t.start(); // display a message box to prevent the // program from ending immediately JOptionPane.showMessageDialog(null, “Click OK to exit program”); System.exit(0); } static class Ticker implements ActionListener ➞ 29 { private boolean tick = true; public void actionPerformed(ActionEvent event) { if (tick) { System.out.println(tickMessage); } else { System.out.println(tockMessage); } tick = !tick; } } } This version of the application and the Listing 7-1 version have only three differences: ➞ 6 The tickMessage field is declared as static. This is necessary so that the static class can access it. ➞ 7 The tockMessage field is also declared as static. ➞ 29 The Ticker class is declared as static. Using Anonymous Inner Classes Anonymous inner classes (usually just called anonymous classes) are proba- bly the strangest feature of the Java programming language. The first time you see an anonymous class, you’ll almost certainly think that someone 25_58961X bk03ch07.qxd 3/29/05 3:44 PM Page 334 Book III Chapter 7 Using Inner Classes Using Anonymous Inner Classes 335 made a mistake, and that the code can’t possibly compile. But compile it does, and it even works. And once you get the hang of working with anony- mous classes, you’ll wonder how you got by without them. An anonymous class is a class that’s defined on the spot, right at the point where you want to instantiate it. Because you code the body of the class right where you need it, you don’t have to give it a name. That’s why it’s called an anonymous class. Creating an anonymous class The basic form for declaring and instantiating an anonymous class is this: new ClassOrInterface() { class-body } As you can see, you specify the new keyword followed by the name of a class or interface that specifies the type of the object created from the anonymous class. This class or interface name is followed by parentheses, which may include a parameter list that’s passed to the constructor of the anonymous class. Then, you code a class body enclosed in braces. This class body can include anything a regular class body can include: fields, methods, even other classes or interfaces. Here’s an example of a simple anonymous class: public class AnonClass { public static void main(String[] args) { Ball b = new Ball() { public void hit() { System.out.println(“You hit it!”); } }; b.hit(); } interface Ball { void hit(); } } In this example, I created an interface named Ball that has a single method named hit. Then, back in the main method, I declared a variable of type Ball and used an anonymous class to create an object. The body of the anonymous class consists of an implementation of the hit method that 25_58961X bk03ch07.qxd 3/29/05 3:44 PM Page 335 Using Anonymous Inner Classes 336 simply displays the message You hit it! on the console. After the anony- mous class is instantiated and assigned to the b variable, the next statement calls the hit method. When you run this program, the single line You hit it! is displayed on the console. Here are some things to ponder when you work with anonymous classes: ✦ You can’t create a constructor for an anonymous class. Because the anonymous class doesn’t have a name, what would you call the con- structor, anyway? ✦ If you list parameters in the parentheses following the class name, Java looks for a constructor in that class that matches the parameters you supply. If it finds one, that constructor is called with the parameters. If not, a compiler error is generated. ✦ You can’t pass parameters if the anonymous class is based on an inter- face. That only makes sense, because interfaces don’t have constructors so Java wouldn’t have anything to pass the parameters to. ✦ An assignment statement can use an anonymous class as shown in this example. In that case, the anonymous class body is followed by a semi- colon that marks the end of the assignment statement. Note that this semicolon is part of the assignment statement, not the anonymous class. (In the next section, you see an example of an anonymous class that’s passed as a method parameter. In that example, the body isn’t followed by a semicolon.) ✦ An anonymous class is a special type of inner class. So, like any inner class, it automatically has access to the fields and methods of its outer class. ✦ An anonymous class can’t be static. Tick Tock with an anonymous class Listing 7-3 shows a more complex example of an anonymous class: a version of the Tick Tock application that uses an anonymous class as the action lis- tener for the timer. LISTING 7-3: TICK TOCK WITH AN ANONYMOUS CLASS import java.awt.event.*; import javax.swing.*; public class TickTockAnonymous { private String tickMessage = “Tick ”; private String tockMessage = “Tock ”; 25_58961X bk03ch07.qxd 3/29/05 3:44 PM Page 336 Book III Chapter 7 Using Inner Classes Using Anonymous Inner Classes 337 public static void main(String[] args) ➞ 9 { TickTockAnonymous t = new TickTockAnonymous(); t.go(); } private void go() { // create a timer that calls the Ticker class // at one second intervals Timer t = new Timer(1000, ➞ 19 new ActionListener() ➞ 20 { ➞ 21 private boolean tick = true; public void actionPerformed( ➞ 24 ActionEvent event) { if (tick) { System.out.println(tickMessage); } else { System.out.println(tockMessage); } tick = !tick; } } ); ➞ 37 t.start(); // display a message box to prevent the // program from ending immediately JOptionPane.showMessageDialog(null, “Click OK to exit program”); System.exit(0); } } By now, you’ve seen enough versions of this program that you should under- stand how it works. The following paragraphs explain how this version uses an anonymous class as the ActionListener parameter supplied to the Timer constructor: ➞ 9 Anonymous classes won’t work in a static context, so the main method creates an instance of the TickTockAnonymous class and executes the go method. ➞ 19 In the go method, an instance of the Timer class is created. 25_58961X bk03ch07.qxd 3/29/05 3:44 PM Page 337 Using Anonymous Inner Classes 338 ➞ 20 The second parameter of the TimerClass constructor is an object that implements the ActionListener interface. This object is cre- ated here via an anonymous class. ActionListener is specified as the type for this class. ➞ 21 This left brace marks the beginning of the body of the anonymous class. ➞ 24 The actionPerformed method is called every 1,000 milliseconds by the timer. Note that this method can freely access fields defined in the outer class. ➞ 37 The right brace on this line marks the end of the body of the anony- mous class. Then, the right parenthesis marks the end of the parameter list for the Timer constructor. The left parenthesis that’s paired with this right parenthesis is on line 19. Finally, the semicolon marks the end of the assignment statement that started on line 19. 25_58961X bk03ch07.qxd 3/29/05 3:44 PM Page 338 [...]... to switch to the directory where you want the pages to reside first For more complete information about using this command, refer to the javadoc documentation at the Sun Web site You can find it at: java. sun.com/j2se/1 .5. 0/docs/guide/javadoc/index.html Using JavaDoc to Document Your Classes 351 Viewing JavaDoc pages After you run the javadoc command, you can access the documentation pages by starting... double-clicking an icon for the jar file Using JavaDoc to Document Your Classes The following sections show you how to add JavaDoc comments to your source files, how to run the source files through the javadoc command, and how to view the resulting documentation pages Adding JavaDoc comments The basic rule for creating JavaDoc comments is that they begin with /** and end with */ You can place JavaDoc comments... Immediately before the declaration of a public class ✦ Immediately before the declaration of a public field ✦ Immediately before the declaration of a public method or constructor Packaging and Documenting Your Classes One last step remains before you can go public with your hot new class library or application: preparing the documentation for its classes Fortunately, Java provides a tool called JavaDoc that... file that can contain more than one class in a compressed format that the Java Runtime Environment can access quickly (JAR stands for Java archive.) A JAR file can have just a few classes in it, or thousands In fact, the entire Java API is stored in a single JAR file named rt .java (The rt stands for runtime.) It’s a pretty big file at over 35MB, but that’s not bad considering that it contains more... look at the documentation for a class, click the class name link A page with complete documentation for the class comes up For example, Figure 8-2 shows part of the documentation page for the Employee class JavaDocs generated this page from the source file shown in Listing 8-1 Book III Chapter 8 Packaging and Documenting Your Classes Figure 8-1: A JavaDocs index page 352 Using JavaDoc to Document Your... this.salary = salary; } } Using the javadoc command The javadoc command has a few dozen options you can set, making it a complicated command to use However, you can ignore all these options to create a basic set of documentation pages Just specify the complete path to all the Java files you want to create documentation for, like this: javadoc com\lowewriter\payroll\* .java The javadoc command creates the documentation... comment for each public class, field, and method, run the source files through the javadoc command and, voila! you have professional-looking Web-based documentation for your classes Book III Chapter 8 348 Using JavaDoc to Document Your Classes A JavaDoc comment can include text that describes the class, field, or method Each subsequent line of a multi-line JavaDoc comment usually begins with an asterisk JavaDoc... a JavaDoc comment can include HTML markup if you want to apply fancy formatting You should avoid using heading tags ( and so on), because JavaDoc creates those and your heading tags just confuse things But you can use tags for boldface and italics ( and ) or to format code examples (use the tag) In addition, you can include special doc tags that provide specific information used by JavaDoc... it from any other paths already in the ClassPath with a semicolon For example: ;c:\javaclasses\utils.jar;c:\javaclasses Here, I added the path c:\javaclasses\utils.jar to my ClassPath variable The first path in a ClassPath variable is always a single dot (.), which allows Java to find classes in the current directory Also, be aware that Java searches the various paths and archive files in the ClassPath... value For example, suppose your ClassPath is already set to this: ;c:\util\classes Packaging and Documenting Your Classes age name Book III Chapter 8 342 Working with Packages Then, you modify it to look like this: ;c:\util\classes;c:\javaclasses Here, I added ;c:\javaclasses to the end of the ClassPath value 5 Save the files for any classes you want to be in a particular package in the directory for . find in the Java bin direc- tory along with the other Java command line tools, such as java and javac. JAR files are similar in format to Zip files, a compressed format made popular 26 _58 961X bk03ch08.qxd. this: .;c:utilclasses;c:javaclasses Here, I added ;c:javaclasses to the end of the ClassPath value. 5. Save the files for any classes you want to be in a particular package in the directory for that package. For. such as c:javaclasses. This folder becomes the root directory for your Java packages. 3. Create subdirectories within the package root directory for your pack- age name. For example, for the package

Ngày đăng: 12/08/2014, 19:21

Xem thêm: Java All-in-One Desk Reference For Dummies phần 5 docx