Java Object-Oriented Programming

Download Report

Transcript Java Object-Oriented Programming

Object-Oriented Programming
Outline
Introduction
Superclasses and Subclasses
protected Members
Relationship between Superclass Objects and Subclass Objects
Constructors and Finalizers in Subclasses
Implicit Subclass-Object-to-Superclass-Object Conversion
Software Engineering with Inheritance
Composition vs. Inheritance
Case Study: Point, Circle, Cylinder
Introduction to Polymorphism
Type Fields and switch Statements
Dynamic Method Binding
Object-Oriented Programming
Outline
final Methods and Classes
Abstract Superclasses and Concrete Classes
Polymorphism Examples
Case Study: A Payroll System Using Polymorphism
New Classes and Dynamic Binding
Case Study: Inheriting Interface and Implementation
Case Study: Creating and Using Interfaces
Inner Class Definitions
Notes on Inner Class Definitions
Type-Wrapper Classes for Primitive Types
Introduction
• Object-Oriented Programming (OOP)
– Inheritance - form of software reusability
• New classes created from existing ones
• Absorb attributes and behaivors, and add in their own
– Override methods - redefine inherited methods
• Subclass inherits from superclass
– Direct superclass - subclass explicitly inherits
– Indirect superclass - subclass inherits from two or more
levels up the class heirarchy
– Polymorphism
• Write programs in a general fashion to handle a wide variety of
classes
– Abstraction - seeing the big picture
Introduction
• Object-Oriented Programming
– Introduce protected member access
– Relationships
• "is a" - inheritance
– Object of subclass "is a" object of the superclass
• "has a" - composition
– Object "has a" object of another class as a member
– Class libraries
• New classes can inherit from them
• Someday software may be constructed from standardized,
reusable components (like hardware)
• Create more powerful software
Superclasses and Subclasses
• Inheritance example
– A rectangle "is a" quadrilateral
• Rectangle is a specific type of quadrilateral
• Quadrilateral is the superclass, rectangle is the subclass
• Incorrect to say quadrilateral "is a" rectangle
– Naming can be confusing because subclass has more
features than superclass
• Subclass more specific than superclass
• Every subclass "is an" object of its superclass, but not viceversa
– Form tree-like hierarchal structures
• Create a hierarchy for class Shape (next slide)
Superclasses and Subclasses
Shape
TwoDimensionalShape
Circle
Square
Triangle
ThreeDimensionalShape
Sphere
Cube
Tetrahedron
• Using inheritance
– Use keyword extends
class TwoDimensionalShape extends Shape{ ... }
– private members of superclass not directly accessible to
subclass
– All other variables keep their member access
protected Members
• In a superclass
– public members
• Accessible anywhere program has a reference to a superclass
or subclass type
– private members
• Accesible only in methods of the superclass
– protected members
• Intermediate protection between private and public
• Only accessible by methods of superclass, of subclass, or
classes in the same package
• Subclass methods
– Can refer to public or protected members by name
– Overridden methods accessible with super.methodName
Modifiers
The following table shows the access to members
permitted by each modifier:
Access Levels
Modifier
Class
Package
Subclass
World
public
Y
Y
Y
Y
protected
Y
Y
Y
N
no modifier
Y
Y
N
N
private
Y
N
N
N
Relationship between Superclass Objects
and Subclass Objects
• Object of subclass
– Can be treated as object of superclass
• Reverse not true
– Suppose many classes inherit from one superclass
• Can make an array of superclass references
• Treat all objects like superclass objects
– Explicit cast
• Convert superclass reference to a subclass reference
(downcasting)
• Can only be done when superclass reference actually referring
to a subclass object
– instanceof operator
• if (p instanceof Circle)
• Returns true if the object to which p points "is a" Circle
Relationship between Superclass Objects
and Subclass Objects
• Overridding methods
– Subclass can redefine superclass methods
• When method mentioned in subclass, subclass version used
• Access original superclass method with super.methodName
– To invoke superclass constructor explicitly
• super(); //can pass arguments if needed
• If called explicitly, must be first statement
• Every Applet has used these techniques
– We have overridden init and paint when we extended
Japplet
• Java implicitly uses class Object as superclass
for all classes
Relationship between Superclass Objects
and Subclass Objects
• Upcoming example
4 public class Point {
– Every class implicitly inheirts from class Object
8
public Point()
– Every constructor must call superclass constructor
• Called implicitly by default
• If explicit, must be first command
41 public class Circle extends Point {
// inherits from Point
– Inherits from Point
54
super( a, b );
// call to superclass constructor
– Explicitly calls superclass (Point) constructor
• Must be first statement in Circle constructor
• To call default superclass construcor, use super()
Relationship between Superclass Objects
and Subclass Objects
– Both Point and Circle override toString
• To call class Point's toString in class Circle
• super.toString()
83
84
Point pointRef, p;
Circle circleRef, c;
88
c = new Circle( 2.7, 120, 89 );
95
pointRef = c;
// assign Circle to pointRef
– pointRef points to a Circle object
• Allowed, because Circle "is a" Point
98
pointRef.toString();
– pointRef knows it is pointing to a Circle object
• Calls the proper toString method
• Example of polymorphism - more later
Relationship between Superclass Objects
and Subclass Objects
102
circleRef = (Circle) pointRef;
– pointRef is pointing to a Circle
• Downcast it to a Circle reference, assign to circleRef
(explicit cast)
87
113
p = new Point( 30, 50 );
if ( p instanceof Circle ) {
– Operator instanceof
• Returns true if object to which p points "is a" Circle
• In this case, returns false
1 // Fig. 9.4: Point.java
2 // Definition of class Point
3
1. Point definition
4 public class Point {
5
protected int x, y; // coordinates of the Point
6
Data members
Point implicitly inherits from1.1
class
7
// No-argument constructor
Object
8
public Point()
9
{
1.2 Constructors
10
// implicit call to superclass constructor occurs here
11
setPoint( 0, 0 );
Notice the default (no argument)
1.3 Methods
12
}
constructor. Implicit call to superclass
13
constructor.
14
// Constructor
15
public Point( int a, int b )
16
{
17
// implicit call to superclass constructor occurs here
18
setPoint( a, b );
19
}
20
21
// Set x and y coordinates of Point
22
public void setPoint( int a, int b )
23
{
24
x = a;
25
y = b;
26
}
27
28
// get x coordinate
29
public int getX() { return x; }
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// get y coordinate
public int getY() { return y; }
// convert the point into a String representation
public String toString()
Class
{ return "[" + x + ", " + y + "]"; }
toString overrides ---------------the original
toString in class Object
1. Circle Definition
}
// Fig. 9.4: Circle.java
// Definition of class Circle
public class Circle extends Point {
protected double radius;
1.4 Overridden
Point's methodtoString method
// inherits from Point
// No-argument constructor
Point constructor called
public Circle()
{
// implicit call to superclass constructor occurs here
setRadius( 0 );
}
1.1 extends Point
1.2 Multiple
implicitly
constructors
// Constructor
Point constructor called explicitly,
public Circle( double r, int a, int b )
and must be the first statement in the
{
subclass constructor
super( a, b ); // call to superclass constructor
setRadius( r );
}
// Set radius of Circle
public void setRadius( double r )
{ radius = ( r >= 0.0 ? r : 0.0 ); }
61
62
// Get radius of Circle
63
public double getRadius() { return radius; }
64
65
// Calculate area of Circle
66
67
public double area() { return Math.PI * radius * radius; }
68
// convert the Circle to a String
69
public String toString()
70
{
71
return "Center = " + "[" + x + ", " + y + "]" +
72
73
74 }
"; Radius = " + radius;
}
1.3 Overridden
toString method
75 // Fig. 9.4: Test.java
76 // Demonstrating the "is a" relationship
77 import java.text.DecimalFormat;
78 import javax.swing.JOptionPane;
1. Initialize objects
79
80 public class InheritanceTest {
81
public static void main( String args[] )
82
{
83
Point pointRef, p;
84
Circle circleRef, c;
85
String output;
2. Refer to a subclass
object with a
superclass reference
2.1 toString
86
87
p = new Point( 30, 50 );
88
c = new Circle( 2.7, 120, 89 );
89
90
91
because
output = "Point p: " + Allowed
p.toString()
+
a subclass object "is a"
object
"\nCircle c: "superclass
+ c.toString();
92
pointRef is actually pointing
to a Circle object, so it calls method toString of class
Circle.
This is an example of polymorphism, more later.
Circle
to pointRef
93
The
that
// use the "is a" relationship
tocomputer
refer toknows
a Circle
94
// with a Point reference
95
pointRef = c;
// assign
96
97
98
output += "\n\nCircle c (via pointRef): " +
pointRef.toString();
99
100
// Use downcasting (casting a superclass reference to a
101
// subclass data type) to assign pointRef to circleRef
102
circleRef = (Circle) pointRef;
103
104
output += "\n\nCircle c (via circleRef): " +
105
circleRef.toString();
106
107
DecimalFormat precision2 = new DecimalFormat(
108
output += "\nArea of c (via circleRef): " +
109
2.2 Downcast
Downcast pointRef (which
is really pointing2.3
to toString
a Circle)
to a Circle, and assign it to
"0.00" );
circleRef
2.4 area
precision2.format( circleRef.area() );
110
111
// Attempt to refer to Point object
112
// with Circle reference
113
if ( p instanceof Circle ) {
114
circleRef = (Circle) p;
115
output += "\n\ncast successful";
// line 40 in Test.java
116
}
117
118
119
120
121
122
123
124
125
126 }
else
output += "\n\np does not refer to a Circle";
JOptionPane.showMessageDialog( null, output,
"Demonstrating the \"is a\" relationship",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
3. if statement
Test if p (class Point) "is a"
Circle. It is not.
Program Output
Constructors and Finalizers in Subclasses
• Objects of subclass
– Superclass constructor should be called
• Initialize superclass variables
– Default constructor called implicitly
• Explicit call (using super) must first command
• If method finalize defined
– Subclass finalize should call superclass finalize as
last action
– Should be protected
• Only subclasses have access
23
protected void finalize()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// Fig. 9.5: Point.java
// Definition of class Point
public class Point extends Object {
protected int x, y; // coordinates of the Point
// no-argument constructor
public Point()
{
x = 0;
y = 0;
System.out.println( "Point constructor: " + this );
}
// constructor
public Point( int a, int b )
{
x = a;
y = b;
Only
subclass
may access
System.out.println( "Point constructor:
" +
this );
}
protected methods.
// finalizer
protected void finalize()
{
System.out.println( "Point finalizer: " + this );
}
// convert the point into a String representation
public String toString()
{ return "[" + x + ", " + y + "]"; }
}
1. Class Point
1.1 Constructors
1.2 Finalizer
(protected)
32 // Fig. 9.5: Circle.java
33 // Definition of class Circle
34 public class Circle extends Point { // inherits from Point
35
protected double radius;
36
37
// no-argument constructor
38
public Circle()
39
{
40
// implicit call to superclass constructor here
41
radius = 0;
42
System.out.println( "Circle constructor: " + this );
43
}
44
45
// Constructor
46
public Circle( double r, int a, int b )
47
{
48
super( a, b ); // call the superclass constructor
49
radius = r;
50
System.out.println( "Circle constructor: " + this );
51
53
// finalizer
54
protected void finalize()
55
{
56
System.out.println( "Circle finalizer: " + this );
57
super.finalize();
59
}
1.1 Constructors
1.2 Finalizer
Circle finalizer calls superclass
finalizer (in Point).
}
52
58
1. Class Circle
(extends Point)
// call superclass finalize method
60
61
// convert the Circle to a String
public String toString()
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
{
return "Center = " + super.toString() +
"; Radius = " + radius;
1. Class Test
}
}
// Fig. 9.5: Test.java
// Demonstrate when superclass and subclass
// constructors and finalizers are called.
public class Test {
public static void main( String args[] )
{
Circle circle1, circle2;
Mark objects for garbage collection by
4.5, setting
72, 29them
); to null.
circle1 = new Circle(
circle2 = new Circle( 10, 5, 5 );
circle1 = null;
circle2 = null;
// mark for garbage collection
// mark for garbage collection
System.gc();
// call the garbage collector
}
}
Call garbage collector (static
method gc of class System).
2. main
2.1 Initialize objects
2.2 System.gc
Point constructor: Center = [72, 29]; Radius = 0.0
Circle constructor: Center = [72, 29]; Radius = 4.5
Point constructor: Center = [5, 5]; Radius = 0.0
Circle constructor: Center = [5, 5]; Radius = 10.0
Circle finalizer: Center = [72, 29]; Radius = 4.5
Point finalizer: Center = [72, 29]; Radius = 4.5
Circle finalizer: Center = [5, 5]; Radius = 10.0
Point finalizer: Center = [5, 5]; Radius = 10.0
Program Output
Implicit Subclass-Object-to-SuperclassObject Conversion
• References to subclass objects
– May be implicitly converted to superclass references
• Makes sense - subclass contains members corresponding to
those of superclass
– Referring to a subclass object with a superclass reference
• Allowed - a subclass object "is a" superclass object
• Can only refer to superclass members
– Referring to a superclass object with a subclass reference
• Error
• Must first be cast to a superclass reference
– Need way to use superclass references but call subclass
methods
• Discussed later in the chapter
Composition vs. Inheritance
• "is a" relationship
– Inheritance
• "has a" relationship
– Composition, having other objects as members
• Example
Employee “is a” BirthDate;
Employee “has a” Birthdate;
//Wrong!
//Composition
Case Study: Point, Circle, Cylinder
• Inheritance example
– Class Point
• protected variables x, y
• Methods: setPoint, getX, getY, toString
– Class Circle (extends Point)
• protected variable radius
• Methods: setRadius, getRadius, area, override
toString
– Class Cylinder (extends Circle)
• protected variable height
• Methods: setHeight, getHeight, area (surface area),
volume, override toString
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// Fig. 9.6: Point.java
// Definition of class Point
package com.deitel.jhtp3.ch09;
public class Point {
protected int x, y; // coordinates of the Point
// no-argument constructor
public Point() { setPoint( 0, 0 ); }
// constructor
public Point( int a, int b ) { setPoint( a, b ); }
// Set
public
{
x =
y =
}
x and y coordinates of Point
void setPoint( int a, int b )
a;
b;
// get x coordinate
public int getX() { return x; }
// get y coordinate
public int getY() { return y; }
// convert the point into a String representation
public String toString()
{ return "[" + x + ", " + y + "]"; }
}
1. Class Point
1.1 Instance variables
2. Constructors
2.1 Methods
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// Fig. 9.7: Circle.java
// Definition of class Circle
package com.deitel.jhtp3.ch09;
public class Circle extends Point {
protected double radius;
// inherits from Point
// no-argument constructor
public Circle()
{
// implicit call to superclass constructor
setRadius( 0 );
}
// Constructor
public Circle( double r, int a, int b )
{
super( a, b ); // call the superclass constructor
setRadius( r );
}
// Set radius of Circle
public void setRadius( double r )
{ radius = ( r >= 0.0 ? r : 0.0 ); }
// Get radius of Circle
public double getRadius() { return radius; }
// Calculate area of Circle
public double area()
{ return Math.PI * radius * radius; }
1. Class Circle
(extends Point)
1.1 Instance variable
2. Constructors
2.1 Methods
32
33
34
35
36
37
38
39 }
// convert the Circle to a String
public String toString()
{
return "Center = " + super.toString() +
"; Radius = " + radius;
}
2.1 Methods
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// Fig. 9.8: Cylinder.java
// Definition of class Cylinder
package com.deitel.jhtp3.ch09;
public class Cylinder extends Circle {
protected double height; // height of Cylinder
// No-argument constructor
public Cylinder()
{
// implicit call to superclass constructor here
setHeight( 0 );
}
1. Class Cylinder
(extends Circle)
1.1 Instance variable
2. Constructors
2.1 Methods
// constructor
public Cylinder( double h, double r, int a, int b )
{
super( r, a, b );
setHeight( h );
}
// Set height of Cylinder
public void setHeight( double h )
{ height = ( h >= 0 ? h : 0 ); }
// Get height of Cylinder
public double getHeight() { return height; }
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44 }
45 //
// Calculate area of Cylinder (i.e., surface area)
public double area()
{
return 2 * super.area() +
2 * Math.PI * radius * height;
}
// Calculate volume of Cylinder
public double volume() { return super.area() * height; }
// Convert the Cylinder to a String
public String toString()
{
return super.toString() + "; Height = " + height;
}
-----------1. Class Test
2. main
Fig. 9.8: Test.java
46 // Application to test class Cylinder
47 import javax.swing.JOptionPane;
48 import java.text.DecimalFormat;
49 import com.deitel.jhtp3.ch09.Cylinder;
50
51 public class Test {
52
public static void main( String args[] )
53
{
54
Cylinder c = new Cylinder( 5.7, 2.5, 12, 23 );
55
DecimalFormat precision2 = new DecimalFormat( "0.00" );
56
String output;
57
2.1 Methods
2.1 Initialize object
58
output = "X coordinate is " + c.getX() +
59
"\nY coordinate is " + c.getY() +
60
"\nRadius is " + c.getRadius() +
61
"\nHeight is " + c.getHeight();
62
63
c.setHeight( 10 );
64
c.setRadius( 4.25 );
65
c.setPoint( 2, 2 );
66
output +=
68
"\n\nThe new location, radius " +
69
"and height of c are\n" + c +
70
"\nArea is " + precision2.format( c.area() ) +
71
"\nVolume is " + precision2.format( c.volume() );
72
73
JOptionPane.showMessageDialog( null, output,
74
"Demonstrating Class Cylinder",
75
JOptionPane.INFORMATION_MESSAGE );
76
78 }
2.3 Set methods
2.4 Display changes
67
77
2.2 Method calls
System.exit( 0 );
}
2.5 area and volume
Program Output
Introduction to Polymorphism
• With polymorphism
– Write extensible programs
– Generically process superclass objects
– Easy to add classes to heirarchy
• Little or no modification required
• Only parts of program that need direct knowledge of new class
must be changed
Type Fields and switch Statements
• switch statements
– Can be used to deal with many objects of different types
• Appropriate action based on type
• Problems
– Programmer may forget to include a type
– Might forget to test all possible cases
– Every addition/deletion of a class requires all switch
statements to be changed
• Tracking all these changes is time consuming and error prone
– Polymorphic programming can eliminate the need for switch
logic
• Avoids all these problems automatically
Dynamic Method Binding
• Dynamic Method Binding
– At execution time, method calls routed to appropriate
version
• Method called for appropriate class
• Example
– Triangle, Circle, and Square all subclasses of
Shape
• Each has an overridden draw method
– Call draw using superclass references
• At execution time, program determines to which class the
reference is actually pointing
• Calls appropriate draw method
final Methods and Classes
• Declaring variables final
– Indicates they cannot be modified after declaration
– Must be initialized when declared
• Declaring methods final
– Cannot be overridden in a subclass
– static and private methods are implicitly final
– Program can inline final methods
• Actually inserts method code at method call locations
• Improves program performance
• Declaring classes final
– Cannot be a superclass (cannot inherit from it)
– All methods in class are implicitly final
Abstract Superclasses and Concrete
Classes
• Abstract classes (abstract superclasses)
– Sole purpose is to be a superclass
• Other classes inherit from it
– Cannot instantiate objects of an abstract class
• Can still have instance variables and constructors
– Too generic to define real objects
– Declare class with keyword abstract
• Concrete class
– Can instantiate objects
– Provide specifics
• Class heirarchies
– Most general classes are usually abstract
• TwoDimensionalShape - too generic to be concrete
Polymorphism Examples
• Class Quadrilateral
– Rectangle "is a" Quadrilateral
– getPerimeter method can be performed on any subclass
• Square, Parallelogram, Trapezoid
• Same method takes on "many forms" - polymorphism
– Have an array of superclass references
• Array would point to all the objects
– Call getPerimeter using the references
• Appropriate method called for each class
• Adding a new subclass
– Simply need to define getPerimeter for that class
– Can refer to it with superclass reference
Polymorphism Examples
• With polymorphism
– New classes can be added easily
– One method call can cause different actions to occur,
depending on object receiving call
• References
– Can create references to abstract classes
• Cannot instantiate objects of abstract classes
• abstract methods
– Keyword abstract
• Any class with an abstract method must be abstract
– abstract methods must be overridden in subclass
• Otherwise, subclass must be abstract
Case Study: A Payroll System Using
Polymorphism
• Example program
– abstract superclass Employee
• abstract method earnings
– Must be implemented in each subclass
– Classes Boss, CommissionWorker, and
PieceWorker, HourlyWorker
• Override methods toString and earnings
– Class Test
• Initialize objects
• Use an Employee reference and call toString and
earnings
• Through polymorphism, the appropriate class method is called
1
2
// Fig. 9.9: Employee.java
// Abstract base class Employee
3
4
5
6
public abstract class Employee {
private String firstName;
private String lastName;
7
8
9
10
11
12
13
14
15
16
17
18
19
20
1. Class Employee
(abstract base class)
Class Employee declared
no Employee
objects can be created.
// Constructor
abstract, so
public Employee( String first, String last )
{
firstName = first;
lastName = last;
}
Employee can still have a
1.2 Methods
constructor, used by its derived
classes.
1.3 earnings
(abstract method)
// Return the first name
public String getFirstName() { return firstName; }
// Return the last name
public String getLastName() { return lastName; }
abstract methods
must be defined in
concrete subclasses.
21
22
23
public String toString()
{ return firstName + ' ' + lastName; }
24
25
26
// Abstract method that must be implemented for each
// derived class of Employee from which objects
// are instantiated.
27
public abstract double earnings();
28 }
1.1 Instance variables
29 // Fig. 9.9: Boss.java
30 // Boss class derived from Employee
31
32 public final class Boss extends Employee {
33
private double weeklySalary;
34
35
// Constructor for class Boss
36
public Boss( String first, String last, double s)
37
{
38
super( first, last );
39
setWeeklySalary( s );
40
// call superclass constructor
}
41
42
// Set the Boss's salary
43
public void setWeeklySalary(
44
45
46
// Get the Boss's pay
47
public double earnings() { return weeklySalary; }
48
// Print the Boss's name
50
public String toString()
51
{
52
53
54 }
return "Boss: " + super.toString();
}
1.1 Instance variable
1.2 Define earnings
(required)
Implementing earnings is required
1.3 Override toString
because it was declared abstract and
double
s )is a concrete class.
Boss
{ weeklySalary = ( s > 0 ? s : 0 ); }
49
1. Class Boss
(extends Employee)
55 // Fig. 9.9: CommissionWorker.java
56 // CommissionWorker class derived from Employee
57
58 public final class CommissionWorker extends Employee {
59
private double salary;
// base salary per week
60
private double commission; // amount per item sold
61
private int quantity;
// total items sold for week
62
63
// Constructor for class CommissionWorker
64
public CommissionWorker( String first, String last,
65
double s, double c, int q)
66
{
67
super( first, last ); // call superclass constructor
68
setSalary( s );
69
setCommission( c );
70
setQuantity( q );
71
}
72
73
// Set CommissionWorker's weekly base salary
74
public void setSalary( double s )
75
{ salary = ( s > 0 ? s : 0 ); }
76
77
// Set CommissionWorker's commission
78
public void setCommission( double c )
79
{ commission = ( c > 0 ? c : 0 ); }
80
81
// Set CommissionWorker's quantity sold
82
public void setQuantity( int q )
83
{ quantity = ( q > 0 ? q : 0 ); }
84
1. Class
CommissionWorker
(extends Employee)
1.1 Instance variables
1.2 Constructor
85
// Determine CommissionWorker's earnings
86
public double earnings()
87
{ return salary + commission * quantity; }
88
89
// Print the CommissionWorker's name
90
public String toString()
91
{
92
return "Commission worker: " + super.toString();
93
}
94 }
95 // Fig. 9.9: PieceWorker.java
96 // PieceWorker class derived from Employee
97
98 public final class PieceWorker extends Employee {
99
private double wagePerPiece; // wage per piece output
100
private int quantity;
// output for week
101
102
// Constructor for class PieceWorker
103
public PieceWorker( String first, String last,
104
double w, int q )
105
{
106
super( first, last ); // call superclass constructor
107
setWage( w );
108
setQuantity( q );
109
}
110
111
// Set the wage
112
public void setWage( double w )
113
{ wagePerPiece = ( w > 0 ? w : 0 ); }
114
1.3 Define earnings
(required)
1.4 Override toString
----------------1. Class PieceWorker
(extends Employee)
1.1 Constructor
115 // Set the number of items output
116
public void setQuantity( int q )
117
{ quantity = ( q > 0 ? q : 0 ); }
118
119
// Determine the PieceWorker's earnings
120
public double earnings()
121
{ return quantity * wagePerPiece; }
122
123
public String toString()
124
{
125
return "Piece worker: " + super.toString();
126
}
127 }
128 // Fig. 9.9: HourlyWorker.java
129 // Definition of class HourlyWorker
130
131 public final class HourlyWorker extends Employee {
132
private double wage;
// wage per hour
133
private double hours; // hours worked for week
134
135
// Constructor for class HourlyWorker
136
public HourlyWorker( String first, String last,
137
double w, double h )
138
{
139
super( first, last );
// call superclass constructor
140
setWage( w );
141
setHours( h );
142
}
143
1.2 Define earnings
(required)
1.3 Override toString
---------------1. Class
HourlyWorker
(extends Employee)
1.1 Constructor
144
// Set the wage
145
public void setWage( double w )
146
{ wage = ( w > 0 ? w : 0 ); }
147
148
// Set the hours worked
149
public void setHours( double h )
150
1.2 Define earnings
(required)
{ hours = ( h >= 0 && h < 168 ? h : 0 ); }
151
1.3 Override toString
152
// Get the HourlyWorker's pay
153
public double earnings() { return wage * hours; }
-----------------------
154
155
public String toString()
156
{
157
158
return "Hourly worker: " + super.toString();
}
159 }
160 // Fig. 9.9: Test.java
161 // Driver for Employee hierarchy
162 import javax.swing.JOptionPane;
References to abstract
classes are allowed.
163 import java.text.DecimalFormat;
164
165 public class Test {
166
public static void main( String args[] )
167
{
168
Employee ref;
169
String output = "";
170
1. Class Test
// superclass reference
1.1 Employee
reference
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
Boss b = new Boss( "John", "Smith", 800.00 );
CommissionWorker c =
new CommissionWorker( "Sue", "Jones",
400.0, 3.0, 150);
1.2 Through
Initialize
PieceWorker p =
Employee reference ref points to Boss object.
new PieceWorker( "Bob",
"Lewis",the
2.5,
200 ); Boss versionsobjects
polymorphism,
appropriate
of
HourlyWorker h =
toString and earnings are called. To check, they are
new HourlyWorker( "Karen", "Price", 13.75, 40 );
called through the Boss object as well.
DecimalFormat precision2 = new DecimalFormat( "0.00" );
ref = b; // Employee reference to a Boss
output += ref.toString() + " earned $" +
precision2.format( ref.earnings() ) + "\n" +
b.toString() + " earned $" +
precision2.format( b.earnings() ) + "\n";
ref = c; // Employee reference to a CommissionWorker
output += ref.toString() + " earned $" +
precision2.format( ref.earnings() ) + "\n" +
c.toString() + " earned $" +
precision2.format( c.earnings() ) + "\n";
ref = p; // Employee reference to a PieceWorker
output += ref.toString() + " earned $" +
precision2.format( ref.earnings() ) + "\n" +
p.toString() + " earned $" +
precision2.format( p.earnings() ) + "\n";
subclass
2. Method calls
through Employee
reference
200
ref = h;
// Employee reference to an HourlyWorker
201
output += ref.toString() + " earned $" +
202
precision2.format( ref.earnings() ) + "\n" +
203
h.toString() + " earned $" +
204
precision2.format( h.earnings() ) + "\n";
205
206
207
JOptionPane.showMessageDialog( null, output,
"Demonstrating Polymorphism",
208
JOptionPane.INFORMATION_MESSAGE );
209
210
2. Method calls
through Employee
reference
System.exit( 0 );
}
211 }
Program Output
New Classes and Dynamic Binding
• Dynamic binding (late binding)
– Accomodates new classes
– Object's type does not need to be known at compile time
– At execution time, method call matched with object
Case Study: Inheriting Interface and
Implementation
• Polymorphism example
– abstract superclass Shape
• Subclasses Point, Circle, Cylinder
• abstract method
– getName
• non-abstract methods
– area (return 0.0)
– volume (return 0.0)
– Class Shape used to define a set of common methods
• Interface is the three common methods
• Implementation of area and volume used for first levels of
heirarchy
Case Study: Inheriting Interface and
Implementation
– Create an array of Shape references
• Point to various subclass objects
• Call methods using Shape reference
159
arrayOfShapes[ i ].getName() + ": " +
160
arrayOfShapes[ i ].toString() +
1
// Fig. 9.10: Shape.java
2
// Definition of abstract base class Shape
3
4
public abstract class Shape extends Object {
5
public double area() { return 0.0; }
6
public double volume() { return 0.0; }
7
public abstract String getName();
8
}
9 // Fig. 9.10: Point.java
10 // Definition of class Point
Methds area and volume are defined.
11
will
12 public class Point extendsThey
Shape
{ be overridden in the subclasses
necessary.
13
protected int x, y; // when
coordinates
of the Point
14
15
// no-argument constructor
16
public Point() { setPoint( 0, 0 ); }
17
18
// constructor
19
public Point( int a, int b ) { setPoint( a, b ); }
20
21
// Set x and y coordinates of Point
22
public void setPoint( int a, int b )
23
{
24
x = a;
25
y = b;
26
}
27
28
// get x coordinate
29
public int getX() { return x; }
30
1. Class Shape
(abstract superclass)
1.1 getName
(abstract method)
---------------------1. Class Point
(extends Shape)
1.1 protected data
members
1.2 Constructors
1.3 New methods
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// get y coordinate
public int getY() { return y; }
// convert the point into a String representation
public String toString()
abstract
{ return "[" + x + ", " + y + "]"; }
1.4 Overridden
method
method getName
must be
getName (required)
overridden in a concrete subclass.
---------------------
// return the class name
public String getName() { return "Point"; }
}
// Fig. 9.10: Circle.java
// Definition of class Circle
public class Circle extends Point {
protected double radius;
1. Class Circle
(extends Point)
// inherits from Point
// no-argument constructor
public Circle()
{
// implicit call to superclass constructor here
setRadius( 0 );
}
// Constructor
public Circle( double r, int a, int b )
{
super( a, b ); // call the superclass constructor
setRadius( r );
}
1.1 protected data
member
1.2 Constructors
1.3 New methods
61
62
63
64
65
66
// Set radius of Circle
public void setRadius( double r )
{ radius = ( r >= 0 ? r : 0 ); }
// Get radius of Circle
public double getRadius() { return radius; }
67
68
69
// Calculate area of Circle
public double area() { return Math.PI * radius * radius; }
70
71
// convert the Circle to a String
72
public String toString()
73
{ return "Center = " +
74
"; Radius = "
75
76
77
1.4 Overridden method
area
1.5 Overridden method
toString
Circle overrides method area,
super.toString()
+ Shape. Point did1.6
inherited from
not Overridden method
getName (required)
+ radius;
}
override
area, and has the default
--------------------implementation (returns 0).
// return the class name
public String getName() { return "Circle"; }
78 }
79 // Fig. 9.10: Cylinder.java
80 // Definition of class Cylinder
81
82 public class Cylinder extends Circle {
83
protected double height; // height of Cylinder
84
85
// no-argument constructor
86
public Cylinder()
87
{
88
// implicit call to superclass constructor here
89
setHeight( 0 );
90
}
Class Cylinder
(extends Circle)
1.1 protected data
member
1.2 Constructors
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122 }
// constructor
public Cylinder( double h, double r, int a, int b )
{
super( r, a, b );
// call superclass constructor
setHeight( h );
}
// Set height of Cylinder
public void setHeight( double h )
{ height = ( h >= 0 ? h : 0 ); }
// Get height of Cylinder
public double getHeight() { return height; }
// Calculate area of Cylinder (i.e., surface area)
public double area()
{
return 2 * super.area() +
2 * Math.PI * radius * height;
}
// Calculate volume of Cylinder
public double volume() { return super.area() * height; }
// Convert a Cylinder to a String
public String toString()
{ return super.toString() + "; Height = " + height; }
// Return the class name
public String getName() { return "Cylinder"; }
1.2 Constructors
1.3 New methods
1.4 Overridden method
area
1.5 Overridden method
toString
1.6 Overridden method
getName
123 // Fig. 9.10: Test.java
124 // Driver for point, circle, cylinder hierarchy
125 import javax.swing.JOptionPane;
Class Test (driver)
126 import java.text.DecimalFormat;
127
128 public class Test {
1. import
129
public static void main( String args[] )
130
{
131
Point point = new Point( 7, 11 );
1.1 Initialize objects
Create
an
array
of
Shape
132
Circle circle = new Circle( 3.5, 22, 8 );
133
Cylinder cylinder = new Cylinder( 10,references.
3.3, 10, 10 );
1.2 Create array of
134
Shape
references
135
Shape arrayOfShapes[];
Point the Shape
references
136
towards subclass objects.
137
arrayOfShapes = new Shape[ 3 ];
1.3 Initialize array
138
139
// aim arrayOfShapes[0] at subclass Point object
140
arrayOfShapes[ 0 ] = point;
2. Call methods using
141
subclass references
142
// aim arrayOfShapes[1] at subclass Circle object
143
arrayOfShapes[ 1 ] = circle;
144
145
// aim arrayOfShapes[2] at subclass Cylinder object
146
arrayOfShapes[ 2 ] = cylinder;
147
148
String output =
149
point.getName() + ": " + point.toString() + "\n" +
150
circle.getName() + ": " + circle.toString() + "\n" +
151
cylinder.getName() + ": " + cylinder.toString();
152
153
DecimalFormat precision2 = new DecimalFormat( "0.00" );
154
155
// Loop through arrayOfShapes and print the name,
156
// area, and volume of each object.
157
for ( int i = 0; i < arrayOfShapes.length; i++ ) {
158
output += "\n\n" +
159
arrayOfShapes[ i ].getName() + ": " +
160
arrayOfShapes[ i ].toString() +
161
"\nArea = " +
162
Call methods
using superclass
precision2.format( arrayOfShapes[
i ].area()
) +
163
"\nVolume = " +
164
precision2.format(
165
references. Appropriate method called
because of
polymorphism.
arrayOfShapes[
i ].volume()
);
}
166
167
JOptionPane.showMessageDialog( null, output,
168
"Demonstrating Polymorphism",
169
JOptionPane.INFORMATION_MESSAGE );
170
171
172
173 }
2.1 Call methods using
Shape references
System.exit( 0 );
}
Program Output
Case Study: Creating and Using Interfaces
• Interface
– Keyword interface
– Has set of public abstract methods
– Can contain public final static data
• Using interfaces
– Class specifies it uses interface with keyword implements
• Multiple interfaces use comma-separated list
– Class must define all abstract methods in interface
• Must use same number of arguments, same return type
– Using interface like signing a contract
• "I will define all methods specified in the interface"
– Same "is a" relationship as inheritance
Case Study: Creating and Using Interfaces
• Using interfaces (continued)
– Interfaces used in place of abstract classes
• Used when no default implementation
– Typically public data types
• Interface defined in its own .java file
• Interface name same as file name
– Previous interfaces
• We have used interface ActionListener
• Required to define actionPerformed
Case Study: Creating and Using Interfaces
• Another use of interfaces
– Define a set of constants used by many classes
public interface Constants {
public static final int ONE = 1;
public static final int TWO = 2;
public static final int THREE = 3;
}
• Reexamine previous heirarchy
– Replace abstract class Shape with interface Shape
1
// Fig. 9.11: Shape.java
2
// Definition of interface Shape
3
4 public interface Shape {
5
public abstract double area();
6
public abstract double volume();
7
public abstract String getName();
8
}
Interface Shape is in its own
file, Shape.java
1. Shape interface
1.1 abstract methods
-----------------------
9 // Fig. 9.11: Point.java
10 // Definition of class Point
11
1. Class Point
12 public class Point extends Object implements Shape {
(implements Shape)
13
protected int x, y; // coordinates of the Point
14
15
// no-argument constructor
16
public Point() { setPoint( 0, 0 ); }
Because Point implements interface
17
Shape, it is required to define the
18
// constructor
19
public Point( int a, int b ) { setPoint( a,abstract
b ); }
methods in Shape.
20
21
// Set x and y coordinates of Point
22
public void setPoint( int a, int b )
23
{
24
x = a;
25
y = b;
26
}
27
28
29
30
31
32
33
34
// get x coordinate
public int getX() { return x; }
35
36
Point required to define the abstract
public String toString()
1.2 Define
{ return "[" + x + ", " + y + "]";
}
methods
of the interface it implements.
37
38
// return the area
39
public double area() { return 0.0; }
40
41
// return the volume
42
public double volume() { return 0.0; }
43
44
45
46 }
// get y coordinate
public int getY() { return y; }
1.1 Define method
area (required)
// convert the point into a String representation
method
volume (required)
1.3 Define method
getName (required)
--------------------// return the class name
public String getName() { return "Point"; }
Class Circle and
Cylinder defined as
before
123 // Fig. 9.11: Test.java
124 // Driver for point, circle, cylinder hierarchy
125 import javax.swing.JOptionPane;
126 import java.text.DecimalFormat;
127
128 public class Test {
129
public static void main( String args[] )
130
{
131
Point point = new Point( 7, 11 );
132
Circle circle = new Circle( 3.5, 22, 8 );
133
Cylinder cylinder = new Cylinder( 10, 3.3, 10, 10 );
134
135
Shape arrayOfShapes[];
136
137
arrayOfShapes = new Shape[ 3 ];
138
139
// aim arrayOfShapes[0] at subclass Point object
140
arrayOfShapes[ 0 ] = point;
141
142
// aim arrayOfShapes[1] at subclass Circle object
143
arrayOfShapes[ 1 ] = circle;
144
145
// aim arrayOfShapes[2] at subclass Cylinder object
146
arrayOfShapes[ 2 ] = cylinder;
147
148
String output =
149
point.getName() + ": " + point.toString() + "\n" +
150
circle.getName() + ": " + circle.toString() + "\n" +
151
cylinder.getName() + ": " + cylinder.toString();
Use same class Test
as before
152
153
DecimalFormat precision2 = new DecimalFormat( "0.00" );
154
155
// Loop through arrayOfShapes and print the name,
156
// area, and volume of each object.
157
for ( int i = 0; i < arrayOfShapes.length; i++ ) {
158
output += "\n\n" +
159
arrayOfShapes[ i ].getName() + ": " +
160
arrayOfShapes[ i ].toString() +
161
"\nArea = " +
162
precision2.format( arrayOfShapes[ i ].area() ) +
163
"\nVolume = " +
164
precision2.format( arrayOfShapes[ i ].volume() );
165
}
166
167
JOptionPane.showMessageDialog( null, output,
168
"Demonstrating Polymorphism",
169
JOptionPane.INFORMATION_MESSAGE );
170
171
172
173 }
System.exit( 0 );
}
Use same class Test
as before
Program Output
Inner Class Definitions
• Inner classes
– Till now, all classes defined at file scope (not inside other
classes)
– Inner classes defined inside other classes
• Can access all members of outer class
• No special handles needed
– Anonymous inner class
• Has no name
– Frequently used with event handling
Inner Class Definitions
• Windowed applications
– Execute an application in its own window (like an applet)
64 public class TimeTestWindow extends JFrame {
• Inherit from class JFrame (javax.swing) rather than
JApplet
• Call constructor to set title: super( "TitleName" )
– init method replaced by constructor
• init not guaranteed to be called (only called for Applets)
• Instead, create GUI components in constructor
• Instantiate object in main (guaranteed to be called)
117
TimeTestWindow window = new TimeTestWindow();
Inner Class Definitions
• Window
Title bar
Minimize, maximize, and close
Inner Class Definitions
123
// INNER CLASS DEFINITION FOR EVENT HANDLING
124
private class ActionEventHandler implements ActionListener {
– Event handling
– Some class must implement interface ActionListener
• Must define method actionPerformed
• Class that implements ActionListener "is an"
ActionListener
79
// create an instance of the inner class
80
85
ActionEventHandler handler = new ActionEventHandler();
hourField.addActionListener( handler );
– Method addActionListener
• Takes object of type ActionListener
• Pass it instance of the class that implements
ActionListener ("is a" relationship)
Inner Class Definitions
• Example
– We will use the Time class and execute an application in its
own window
– Use event handling to set the time
• Define an inner class that implements ActionListener
• Use an object of this class as the event handler
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// Fig. 9.12: Time.java
// Time class definition
import java.text.DecimalFormat;
// used for number formatting
// This class maintains the time in 24-hour format
public class Time extends Object {
private int hour;
// 0 - 23
private int minute;
// 0 - 59
private int second;
// 0 - 59
// Time constructor initializes each instance variable
// to zero. Ensures that Time object starts in a
// consistent state.
public Time() { setTime( 0, 0, 0 ); }
// Set a new time value using universal time. Perform
// validity checks on the data. Set invalid values to zero.
public void setTime( int h, int m, int s )
{
setHour( h );
// set the hour
setMinute( m ); // set the minute
setSecond( s ); // set the second
}
// set the hour
public void setHour( int h )
{ hour = ( ( h >= 0 && h < 24 ) ? h : 0 ); }
// set the minute
public void setMinute( int m )
{ minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); }
1. Time class
1.2 Data members
1.3 Constructors
1.4 Methods
32
33
// set the second
34
35
36
37
38
39
40
41
42
43
44
45
46
public void setSecond( int s )
{ second = ( ( s >= 0 && s < 60 ) ? s : 0 ); }
47
public String toString()
48
{
1.4 Methods
// get the hour
public int getHour() { return hour; }
// get the minute
public int getMinute() { return minute; }
// get the second
public int getSecond() { return second; }
// Convert to String in standard-time format
49
DecimalFormat twoDigits = new DecimalFormat( "00" );
50
51
return ( ( getHour() == 12 || getHour() == 0 ) ?
52
12 : getHour() % 12 ) + ":" +
53
twoDigits.format( getMinute() ) + ":" +
54
twoDigits.format( getSecond() ) +
55
( getHour() < 12 ? " AM" : " PM" );
56
57 }
}
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// Fig. 9.12: TimeTestWindow.java
// Demonstrating the Time class set and get methods
import java.awt.*;
Set up all GUI components in
import java.awt.event.*;
constructor. In main, create a
import javax.swing.*;
TimeTestWindow object, which
extends
{
runs theJFrame
constructor.
public class TimeTestWindow
private Time t;
private JLabel hourLabel, minuteLabel, secondLabel;
Call to JFrame constructor
private JTextField hourField, minuteField,
of window.
secondField,
display;
private JButton exitButton;
sets title bar
public TimeTestWindow()
{
super( "Inner Class Demonstration" );
1. import
1.1 Class
TimeTestWindow (
extends JFrame)
1.2 Create GUI
components in
constructor
1.3 Create instance of
t = new Time();
class that implements
ActionListener
Object of inner class ActionEventHandler
Container c = getContentPane();
passed as an argument to addActionListener
// create an instance of the inner class
ActionEventHandler handler = new ActionEventHandler();
c.setLayout( new FlowLayout() );
hourLabel = new JLabel( "Set Hour" );
hourField = new JTextField( 10 );
hourField.addActionListener( handler );
c.add( hourLabel );
c.add( hourField );
1.4
addActionListener
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
minuteLabel = new JLabel( "Set minute" );
minuteField = new JTextField( 10 );
minuteField.addActionListener( handler );
c.add( minuteLabel );
c.add( minuteField );
secondLabel = new JLabel( "Set Second" );
secondField = new JTextField( 10 );
secondField.addActionListener( handler );
c.add( secondLabel );
c.add( secondField );
display = new JTextField( 30 );
display.setEditable( false );
c.add( display );
1.5 Create GUI
components
2. Methods
3. main
3.1 Create object
exitButton = new JButton( "Exit" );
exitButton.addActionListener( handler );
c.add( exitButton );
}
public void displayTime()
Create
{
display.setText( "The time is: " + t );
}
public static void main( String args[] )
{
TimeTestWindow window = new TimeTestWindow();
TimeTestWindow object.
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148 }
window.setSize( 400, 140 );
window.show();
}
// INNER CLASS DEFINITION FOR EVENT HANDLING
4. Inner class
private class ActionEventHandler implements ActionListener {
ActionEventHandler
public void actionPerformed( ActionEvent e )
implements
{
ActionListener
if ( e.getSource() == exitButton )
System.exit( 0 );
// terminate the application
else if ( e.getSource() == hourField ) {
t.setHour(
Use a named
Integer.parseInt( e.getActionCommand()
) ); inner class as the event
hourField.setText( "" );
handler. Class implements interface
}
ActionListener, and must define
else if ( e.getSource() == minuteField )
{
actionPerformed.
t.setMinute(
Integer.parseInt( e.getActionCommand() ) );
minuteField.setText( "" );
}
else if ( e.getSource() == secondField ) {
t.setSecond(
Integer.parseInt( e.getActionCommand() ) );
secondField.setText( "" );
}
displayTime();
}
}
Program Output
Inner Class Definitions
• Anonymous inner classes
– Have no name
– Object created at time class defined
• Event handling with anonymous inner classes
– Define the inner class inside the call to
addActionListener
• Create an instance of the class inside the method call
• addActionListener takes an object of class
ActionListener
Inner Class Definitions
24
hourField.addActionListener(
25
new ActionListener() {
// anonymous inner class
26
public void actionPerformed( ActionEvent e )
27
{
28
t.setHour(
29
30
31
32
33
34
Integer.parseInt( e.getActionCommand() ) );
hourField.setText( "" );
displayTime();
}
}
);
– new creates an object
– ActionListener()
• Begins definition of anonymous class and calls default
constructor
• Similar to
public class myHandler implements ActionListener
– Braces ( {} ) begin and end class defintion
Inner Class Definitions
82
84
85
86
TimeTestWindow window = new TimeTestWindow();
window.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
87
{
88
System.exit( 0 );
89
}
90
91
}
);
– Enables use of close box (window closing event)
• addWindowListener registers window event listener
• 7 methods need to be defined for interface
WindowListener
• Adapter classes - already implement interfaces
– Extend adapter class and override methods want to define
• Adapter class "is a" WindowListener
Inner Class Definitions
82
84
85
86
TimeTestWindow window = new TimeTestWindow();
window.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
87
{
88
System.exit( 0 );
89
}
90
91
}
);
– new WindowAdapter()
• Begins anonymous inner class that extends WindowAdapter
• Similar to:
public class myHandler extends WindowAdapter {
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// Fig. 9.13: TimeTestWindow.java
// Demonstrating the Time class set and get methods
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TimeTestWindow extends JFrame {
private Time t;
private JLabel hourLabel, minuteLabel, secondLabel;
private JTextField hourField, minuteField,
secondField, display;
public TimeTestWindow()
{
super( "Inner Class Demonstration" );
1.2 Constructor
t = new Time();
Container c = getContentPane();
An object of an anonymous inner
class handler (
2. Event
is used as the event handler. anonymous inner
c.setLayout( new FlowLayout() );
hourLabel = new JLabel( "Set Hour" );
hourField = new JTextField( 10 );
hourField.addActionListener(
new ActionListener() {
// anonymous inner class
public void actionPerformed( ActionEvent e )
27
{
29
1.1 Class
TimeTestWindow
(extends JFrame)
1.3 Initialze GUI
26
28
1. import
t.setHour(
Integer.parseInt( e.getActionCommand() ) );
class)
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
hourField.setText( "" );
displayTime();
}
}
);
c.add( hourLabel );
c.add( hourField );
2. Event handler (
Each button has a separate inner
class
anonymous
inner
as an event handler.
class)
minuteLabel = new JLabel( "Set minute" );
minuteField = new JTextField( 10 );
minuteField.addActionListener(
new ActionListener() { // anonymous inner class
public void actionPerformed( ActionEvent e )
{
t.setMinute(
Integer.parseInt( e.getActionCommand() ) );
minuteField.setText( "" );
displayTime();
}
}
);
c.add( minuteLabel );
c.add( minuteField );
secondLabel = new JLabel( "Set Second" );
secondField = new JTextField( 10 );
secondField.addActionListener(
new ActionListener() { // anonymous inner class
public void actionPerformed( ActionEvent e )
59
60
{
t.setSecond(
Integer.parseInt( e.getActionCommand() ) );
secondField.setText( "" );
displayTime();
61
62
63
64
65
66
67
);
c.add( secondLabel );
68
c.add( secondField );
3. main
}
}
3.1 Create
TimeTestWindow
object
69
70
display = new JTextField( 30 );
71
display.setEditable( false );
72
c.add( display );
73
3.2
addWindowListener
}
74
75
76
77
78
79
80
81
82
83
84
85
public void displayTime()
{
display.setText( "The time is: " + t );
}
Use an anonymous inner class
) to handle window events.
public static void main( String args[]
{
TimeTestWindow window = new TimeTestWindow();
window.addWindowListener(
new WindowAdapter() {
86
public void windowClosing( WindowEvent e )
87
{
88
System.exit( 0 );
89
}
90
}
91
);
92
93
window.setSize( 400, 120 );
94
window.show();
95
}
96 }
Program Output
Notes on Inner Class Definitions
• Notes
– Every class (including inner classes) have their own
.class file
– Named inner classes can be public, protected,
private, or have package access
• Same restrictions as other members of a class
– To access outer class's this reference
• OuterClassName.this
– Inner class can be static
• Does not have access to outer class's non-static members
Notes on Inner Class Definitions
• Notes (continued)
– To create an object of another class's inner class
• Create an object of outer class and assign it a reference (ref)
• Type statement of form:
OuterClassname ref = new OuterClassname();
OuterClassName.InnerClassName innerRef = ref.new
InnerClassName();
Type-Wrapper Classes for Primitive Types
• Type wrapper classes
– Each primitive data type has one
• Called Character, Byte, Short, Integer, Long,
Float, Double, Boolean
– Manipulate primitive types like objects of class Object
• Values can be processed polymorphically
– Declared final, so methods implicitly final
• Cannot be overridden
– Numeric classes inherit from Number
• Byte, Short, Integer, Long, Float, Double
– Many methods are static
– Check documentation if manipulating primitive types
• Method you need may be defined