Java Reference
In-Depth Information
would need to be defined. You use this approach in practice when you are implementing window-based ap-
plications later in the topic.
If the anonymous class extends an existing class, the syntax is much the same. In this case, you are calling
a constructor for the base class, and if this is not a default constructor, you can pass arguments to it by spe-
cifying them between the parentheses following the base class name. The definition of the anonymous class
must appear between braces, just as in the previous example.
An anonymous class can be convenient when the class definition is short and simple. You shouldn't use
the approach to define classes of any complexity as it makes the code very difficult to understand.
SUMMARY
You should now understand polymorphism and how to apply it. You will find that this technique can be
utilized to considerable advantage in the majority of your Java programs. It certainly appears in many of the
examples in the remaining chapters.
EXERCISES
You can download the source code for the examples in the topic and the solutions to the following exer-
cises from www.wrox.com .
1. Define an abstract base class Shape that includes protected data members for the ( x , y ) position of
a shape, a public method to move a shape, and a public abstract method show() to output a shape.
Derive subclasses for lines, circles, and rectangles. Also, define the class PolyLine that you saw in
this chapter with Shape as its base class. You can represent a line as two points, a circle as a center
and a radius, and a rectangle as two points on diagonally opposite corners. Implement the toString()
method for each class. Test the classes by selecting ten random objects of the derived classes, and then
invoking the show() method for each. Use the t oString() methods in the implementation of show()
in the derived classes.
2. Define a class, ShapeList , that can store an arbitrary collection of any objects of subclasses of the
Shape class.
3. Implement the classes for shapes using an interface for the common methods, rather than inheritance
from the superclass, while still keeping Shape as a base class.
4. Extend the LinkedList class that you defined in this chapter so that it supports traversing the list
backward as well as forward.
5. Add methods to the class LinkedList to insert and delete elements at the current position.
6. Implement a method in the LinkedList class to insert an object following an object passed as an ar-
gument. Assume the objects stored in the list implement an equals() method that compares the this
object with an object passed as an argument and returns true if they are equal.
• WHAT YOU LEARNED IN THIS CHAPTER
Search WWH ::




Custom Search