Java Reference
In-Depth Information
So far, we have completed steps 1 through 3. In the constructor method, we will now add the WindowListener
(UsefulFrame) to itself. You may be wondering why we do this in the constructor. Another nuance of Java is that
whenever an object is created, the object's superclass constructor is automatically called by the JVM. In other words,
when an EmpFrame is created, the Frame class's constructor method is called. We will use this feature so that all
UsefulFrame subclasses automatically add the window listener and define a default size and location.
12.
Add the following constructor after the class header but before the seven methods:
public UsefulFrame () {
this .setBounds(350, 200, 400, 400);
this .addWindowListener( this );
}
Notice the default size is defined as 400 by 400, and the frame has been positioned at X = 350 and Y = 200 pixels,
which centers it on the screen that is set at a resolution of 1024 by 768.
13.
Save the UsefulFrame source code.
Tutorial: Creating a Subclass
Because UsefulFrame has all sorts of nifty code that we want included in EmpFrame, we need to define EmpFrame
as a subclass of UsefulFrame.
In EmpFrame, change the extends clause from Frame to UsefulFrame.
1.
2.
Save the EmpFrame source code and run EmployeeApp.
3.
Click the close button.
Pretty cool! The listener/sentry was on the job!
4.
Run EmployeeApp again.
Notice that EmpFrame is not centered on the screen and does not seem to be 400 by 400. This is because
EmpFrame sets the bounds as 10, 10, 300, 300. This highlights a second characteristic of the superclass/subclass
relationship: subclass values and methods override inherited superclass values and methods. In other words,
the EmpFrame setBounds statement overrode the superclass's setBounds statement. Let's prove that the subclass
overrides the superclass.
5.
In EmpFrame, comment out the frame's setBounds statement, save the source code,
and run EmployeeApp.
The screen should look like Figure 4-1 .
 
Search WWH ::




Custom Search