Webswing
Webswing
Student Workbook
Java Swing
Java Swing
Published by ITCourseware, LLC, 7245 South Havana Street, Suite 100, Englewood, CO 80112
Contributing Authors: Channing Lovely, Rob Roselius, Rick Sussenbach, Danielle Waleri.
Special thanks to: Many Java instructors whose ideas and careful review have contributed to the quality
of this workbook, including Jimmy Ball, Larry Burley, Julie Johnson, Roger Jones, Joe McGlynn, Jim
McNally, Richard Raab, and Todd Wright, and the many students who have offered comments,
suggestions, criticisms, and insights.
Copyright © 2002 by ITCourseware, LLC. All rights reserved. No part of this book may be reproduced
or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by
an information storage retrieval system, without permission in writing from the publisher. Inquiries should be
addressed to ITCourseware, LLC, 7245 South Havana Street, Suite 100, Englewood, CO 80112. (303)
302-5280.
All brand names, product names, trademarks, and registered trademarks are the property of their respective
owners.
Contents
Chapter 1 - Course Introduction ............................................................................................................... 7
Course Objectives .............................................................................................................................. 8
Course Overview .............................................................................................................................. 10
Using the Workbook ......................................................................................................................... 11
Suggested References ....................................................................................................................... 12
Index..................................................................................................................................................... 325
Page vi Rev 4.1.2 © 2002 ITCourseware, LLC
Chapter 4 Inner Classes
Objectives
Inner Classes
Ø This syntax allows for quick and easy creation of classes for specific
purposes.
¯ The class that contains the inner class is called the enclosing class or the
enclosing instance (depending on the type of inner class).
Ø Two enclosing classes can each have an inner class with exactly the same
name.
Ø They can't have the same name as any containing class or package (unlike
fields and methods).
Ø Member classes.
Ø Local classes.
Ø Anonymous classes.
The Java compiler compiles inner classes as "normal" classes, changing their names to ensure uniqueness
and indicate scope, and usually adding some code to them to make them work as described. Because the
compiler does this work, the Java Virtual Machine has not needed to be modified. This means that older
VMs will run code that uses inner classes.
The only thing that you, as a programmer, might notice are some strange .class files. Suppose that you have
a .java file with a class called MyOuter that has an inner class called MyInner. The compiler will create
a MyOuter.class file and a MyOuter$MyInner.class file. Don't use this name in your code at all. The
compiler takes care of everything!
Member Classes
¯ A class defined within an enclosing class, but without the static keyword, is a
member class.
¯ Every instance of the member class has an internal reference to the enclosing
object.
Ø A method in the member class can use its own data and the data in the
enclosing instance (including private fields), implicitly, without any
special syntax.
¯ You must specify an enclosing instance when creating a member instance from
another class.
¯ Member class methods can explicitly refer to the enclosing instance's data using
the enclosing class name along with this:
class Teller {
...
public string toString() {
String ret = "Bank #" + Bank1.this.bankId;
...
Bank1.java
import java.util.*;
class Teller {
private String lastname;
private String firstname;
private int accessLevel;
RunBank1.java
import java.util.*;
Local Classes
¯ A class defined within a code block is a local class; examples of code blocks
include:
Ø Methods
Ø Constructors
Ø It is visible only within the code block in which it is defined, just like a
local variable.
Ø It can only use final method parameters or final local variables that
are within the same scope.
¯ A local class has access to member data and methods of the enclosing class,
just like a member class does.
Ø If the local class is within the static initialization block or method, then
it only has access to static fields.
Ø The definition and use of the class can be one after the other, making the
code more readable.
RunBank1Local.java
import java.util.*;
Local classes are often used to handle events in graphical Swing programs, implementing the method or
methods declared in an event listener interface:
Welcome.java
...
JButton bye = new JButton("Bye");
JButton adios = new JButton("Adios");
class ExitListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
f.dispose();
System.exit(0);
}
}
bye.addActionListener( new ExitListener() );
adios.addActionListener( new ExitListener() );
...
Anonymous Classes
¯ Anonymous classes combine the class definition with the object instantiation.
¯ Additional syntax for the new operator was introduced to allow for anonymous
classes.
Ø If Name is a class name, then the anonymous class extends that class
and can provide constructor arguments.
RunBank1Anon.java
import java.util.*;
Anonymous classes are perfect for special-purpose event handlers for individual Swing components:
Welcome2.java
...
bye.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
f.dispose();
System.exit(0);
}
});
...
Instance Initializers
Ø Multiple instance initializers are allowed; they are run from top to bottom.
Ø They run after the superclass constructor, and before the current class'
constructor (if it isn't anonymous).
¯ The initialization of a data member can be done immediately after the declaration
of the variable.
Bank2.java
import java.util.*;
public class Bank2 {
int bankId;
class Teller {
private String lastname;
private String firstname;
protected int accessLevel;
Teller(String l, String f) {
lastname = l;
firstname = f;
accessLevel = 3;
}
public String toString() {
String ret = "Bank #" + bankId;
ret = ret + " " + firstname + " " + lastname + " : " + accessLevel;
return ret;
}
}
Bank2(int id) { bankId = id; }
public String toString() { return "Bank ID: " + bankId; }
}
RunBank2.java
import java.util.*;
Nested Classes
Ø Nested top-level classes were introduced in Java 1.1, but are not inner
classes and do not have the restrictions of inner classes.
¯ Nested top-level classes have the same visibility as any other class within a
package.
Bank3.Teller t3 =
new Bank3.Teller("Doe", "Jane", 4);
¯ This nesting provides a new namespace; two classes can both contain nested top-
level classes with the same name.
¯ Interfaces defined within a class are implicitly static and are therefore top-level.
Bank3.java
import java.util.*;
Bank3(Vector t) {
tellers = t;
}
RunBank3.java
import java.util.*;
Note: Nested top-level classes and interfaces are not considered true inner classes because they actually
have package scope. But they are commonly referred to in conjunction with inner classes since they were
introduced at the same time.
© 2002 ITCourseware, LLC Rev 4.1.2 Page 69
Java Swing
¯ Inner classes may inherit from any class that is visible within its scope.
Ø Top-level classes may also inherit from inner classes that are visible,
although this is not as common.
Business.java
public class Business {
private class Employee extends Person {
Labs
❶ Create a Department class with an Employee member class. The Employee class should
have data members for id, firstname, lastname, title and salary. Add a constructor
and display() method to Employee.
(Solution: Department.java)
❷ Modify the Department class. Add data members for an array of Employee objects, a
department code and a department name. Add a constructor that takes two arguments, the
department code and name.
The constructor would normally then initialize it's Employee array from a database, but just add
several "dummy" Employee objects to the array. Write a display() method for the
Department.
(Solution: Department1.java)
❹ Next, let's make our Department and Employee classes more useful from other classes. First,
remove the main() method from your Department class.
Add a method to Employee named getSalary() that returns the Employee's salary.
In another file, create a Headquarters class that has a main() method. In main(), create a
new Department object and display() it. Then get the Employee[] from that
Department by calling getEmployees(). Display the salary of the highest-paid employee.
Hint: For Headquarters to use the Employee class, it will have to be made
a public member of Department.
(Solutions: Department3.java, Headquarters.java)