Java Reference
In-Depth Information
As that worked well for our need to display some text, why bother with this superclass/subclass thing? The reason is
that often you will want a JRE supplied class to “do more” than setting properties and adding components can provide.
For instance, our frame needs source code to make the Close button work. You can't add a “close button” function to
the Frame object. In addition, if an extensively “tailored” object will be useful to many other classes, it is better to specify
the “tailoring” commands once in a subclass than to duplicate the commands in multiple classes. Finally, classes are
often created to hold common functions that many classes will use. This repository of common functions is then used
as a superclass so that many subclasses can inherit these functions. This not only saves on the amount of coding but any
changes to these common functions are made once in the superclass rather than in many classes.
This does not mean that you should always create subclasses. If a class exists:
1.
Whose property values can be set to meet your needs and
2.
This particular set of property values will not be needed by other classes
simply instantiate an object of that class type. Notice that in previous examples String objects were created
rather than subclasses. The reason objects were used is that the String class has all the functions and properties that
we needed. Also, any String properties we did specify (like the employee name) would not be reused in other classes.
In other words, the strings we created had a limited scope of use, therefore; there was no benefit in creating a subclass.
Frames, however, often need to be customized and reused to such an extent that subclasses are the best choice.
Tutorial: Creating a Frame Subclass
We will create an EmpFrame class to perform the display function and remove that function from the Employee class.
We will also change the Employee class to hold more information about an employee and store the information in
properties.
The following summarizes the statements used to create and define a Frame object in the earlier example:
A.
Import the java.awt.Frame class
B.
Create a Frame variable and object then assign the object to the variable
C.
Define a title
D.
Set the layout property to null
E.
Define the size
F.
Define the location
G.
Make the frame visible
This time we are going to create a Frame subclass called EmpFrame instead of instantiating a Frame object.
Inside the EmpFrame class, we will define all the properties thereby eliminating the need to perform steps C through
G for any class that uses EmpFrame. When another class wants to use EmpFrame, they will only have to import the
EmpFrame class and create an EmpFrame object (statements A and B).
1.
Select c3 in Tutorials and click File, New, and then Class.
The New Java Class frame will be displayed (see Figure 3-11 ).
 
Search WWH ::




Custom Search