Java Reference
In-Depth Information
Display 13.11
Anonymous Classes (part 2 of 2)
26 public int getNumber()
27 {
28
return number;
29 }
30 };
31 anObject.setNumber(42);
32 anotherObject.setNumber(42);
33 showNumber(anObject);
34 showNumber(anotherObject);
35 System.out.println("End of program.");
36 }
37 public static void showNumber(NumberCarrier o)
38 {
39 System.out.println(o.getNumber());
40 }
This is the file AnonymousClassDemo.java .
41 }
Sample Dialogue
42
84
End of program.
This is the file NumberCarrier.java .
1 public interface NumberCarrier
2 {
3
public void setNumber( int value);
4
public int getNumber();
5 }
TIP: Why Use Inner Classes?
Most simple situations do not need inner classes. However, there are situations for
which inner classes are a good solution. For example, suppose you want to have a
class with two base classes. This is not allowed in Java. However, you can have an
outer class derived from one base class with an inner class derived from the other base
class. Because the inner and outer classes have access to each other's instance variables
and methods, this can often serve as if it were a class with two base classes.
As another example, if you need only one object of a class and the class definition
is very short, many programmers like to use an anonymous class (but I must admit I
am not one of them).
When we study linked lists in Chapter 15, you will see cases where using an inner
class as a helping class makes the linked list class self-contained in a very natural
way. We will also use inner classes when defining Graphical User Interfaces (GUIs)
starting in Chapter 17. But until you learn what linked lists and GUIs are, these are
not likely to be compelling examples.
 
 
Search WWH ::




Custom Search