Java Reference
In-Depth Information
Specialization vs. Composition
How do you decide whether to modify the properties of a component object or create a subclass with unique
properties? Unfortunately, it is not clear-cut and many times the programmer makes the decision on a case-by-case
basis. For instance, should you create a
Frame
subclass or simply create a
Frame
object and modify its properties? In
the case of EmpFrame, modifying the properties of a
Frame
object would not meet our requirements, so we had to
define a specialized frame (EmpFrame).
We then created another
Frame
subclass (UsefulFrame) to hold all our default frame properties and methods.
When we establish an “is a” (superclass/subclass) relationship between UsefulFrame and our other frames, we will
cut down on the amount of programming needed and ensure consistency across all our frames. Both of these benefits
are important goals of object-oriented programming.
To reiterate, we created UsefulFrame (as a
Frame
subclass) to act as a repository of source code because:
Frame
object could not be modified to perform those functions
•
A
•
The functions and properties defined in UsefulFrame need to be applied to all frames in the
application
Have you noticed that UsefulFrame, despite its name, really doesn't do anything? It is simply a class that has the
common attributes we want in all our frames. No UsefulFrame object will ever be created or displayed. Classes like
UsefulFrame are known as
abstract
classes.
Unlike frames, most other GUI components (buttons, labels, etc.) are specific enough that we simply create
instances, modify their properties, and add them to a frame (composition). However, there are instances where you
might want to create subclasses of these components. For example, creating an ExitButton class that always appears
in the lower right corner of every frame would be a useful subclass of Button. Why, you ask? Well, instead of defining
an exit button's text, function, and location for every frame, we could define it once in a subclass. Then, instead of
adding an exit button to every frame, we will add it to UsefulFrame. This way every UsefulFrame subclass will have an
exit button and we don't have to enter the code many times.
Tutorial: Creating the ExitButton Class
Let's get started:
1.
Create a new class in Tutorials/c4 called ExitButton. Define the superclass as java.awt.
Button, and do not have any other methods or stubs generated.
The code should look like the following:
package
c4;
import
java.awt.Button;
public class
ExitButton
extends
Button {
}
Like most visual classes, a button's location and size are set by the setBounds statement. To define the text that
will appear on the button, the setLabel method is used.
2.
Add the following statements to create a constructor and initialize the button:
public
ExitButton() {
this
.setBounds(350, 370, 40, 20);
this
.setLabel("Exit");
}