Object-Oriented Programming Outline Introduction Superclasses and Subclasses protected Members Relationship between Superclass Objects and Subclass Objects.

Slides:



Advertisements
Similar presentations
Chapter 19 - Inheritance Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
Advertisements

 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - Object-Oriented Programming: Polymorphism Outline 10.1 Introduction 10.2 Relationships Among.
Chapter 20- Virtual Functions and Polymorphism Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng.
1 Chapter 9 - Object-Oriented Programming: Inheritance Outline 9.1 Introduction 9.2 Superclasses and Subclasses 9.3 protected Members 9.4 Relationship.
Inheritance Java permits you to use your user defined classes to create programs using inheritance.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 27 - Java Object-Oriented Programming Outline 27.1Introduction 27.2Superclasses and Subclasses.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 9 - Object-Oriented Programming: Inheritance Outline 9.1 Introduction 9.2 Superclasses and Subclasses.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 27 - Java Object-Oriented Programming Outline.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 20- Virtual Functions and Polymorphism Outline 20.1Introduction 20.2Type Fields and switch Statements.
1 Chapter 10 - Object-Oriented Programming: Polymorphism Outline 10.1 Introduction 10.2 Relationships Among Objects in an Inheritance Hierarchy
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Chapter 8 – Sections covered
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - Object-Oriented Programming: Polymorphism Outline 10.1 Introduction 10.2 Relationships Among.
Object-Oriented Programming: Polymorphism
Unit 5 School of Information Systems & Technology1 School of Information Systems and Technology (IST)
Chapter 9 - Object-Oriented Programming
 2005 Pearson Education, Inc. All rights reserved Object-Oriented Programming: Inheritance.
1 Abstract Class There are some situations in which it is useful to define base classes that are never instantiated. Such classes are called abstract classes.
 2002 Prentice Hall. All rights reserved. Page 1 Chapter 9 - Object-Oriented Programming 9.10 Introduction to Polymorphism 9.11 Type Fields and switch.
Interfaces Need arising from software engineering –Disparate groups of programmers need to agree to a “contract” that spells out how their software interacts.
CISC6795: Spring Object-Oriented Programming: Polymorphism.
(C) 2010 Pearson Education, Inc. All rights reserved. Java™ How to Program, 8/e.
Lecture 9 Polymorphism Richard Gesick.
Advanced Programming Collage of Information Technology University of Palestine, Gaza Prepared by: Mahmoud Rafeek Alfarra Lecture 1: Course overview.
 2002 Prentice Hall. All rights reserved. Chapter 9 - Object-Oriented Programming Outline 9.1 Introduction 9.2 Superclasses and Subclasses 9.3 protected.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
1 Object-Oriented Programming: Polymorphism 10.1 Introduction 10.2 Relationships Among Objects in an Inheritance Hierarchy Invoking Superclass Methods.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Inheritance and Polymorphism.
More on Hierarchies 1. When an object of a subclass is instantiated, is memory allocated for only the data members of the subclass or also for the members.
1 OOP : main concepts Polymorphism. 2 OOP : main concepts  The main concepts:  In a superclass –public members Accessible anywhere program has a reference.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 20 - C++ Virtual Functions and Polymorphism.
1 Chapter 5 - Object-Oriented Programming 1 What is inheritance? Object-oriented systems allow classes to be defined in terms of other classes. Classes.
 All calls to method toString and earnings are resolved at execution time, based on the type of the object to which currentEmployee refers.  Known as.
 2003 Prentice Hall, Inc. All rights reserved Case Study: Three-Level Inheritance Hierarchy Three level point/circle/cylinder hierarchy –Point.
Inheritance & Polymorphism1. 2 Introduction Besides composition, another form of reuse is inheritance. With inheritance, an object can inherit behavior.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 9 - Inheritance Outline 9.1Introduction 9.2Inheritance: Base Classes and Derived Classes 9.3.
 2002 Prentice Hall. All rights reserved. Modifed by Haytham Allos, NYU CSD V Week 2 - Object-Oriented Programming Outline 2.1 Introduction 2.2.
Chapter 14 Abstract Classes and Interfaces. Abstract Classes An abstract class extracts common features and functionality of a family of objects An abstract.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 9 - Object-Oriented Programming: Inheritance Outline 9.1 Introduction 9.2 Superclasses and Subclasses.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 26 - Java Object-Based Programming Outline 26.1Introduction.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
1 The finalize, clone, and getClass Methods  The finalize method is invoked by the garbage collector on an object when the object becomes garbage.  The.
1 Chapter 3 – Object-Based Programming 2 Initializing Class Objects: Constructors Class constructor is a specical method to initialise instance variables.
Object Oriented Programming
Chapter 7: Class Inheritance F Superclasses and Subclasses F Keywords: super and this F Overriding methods F The Object Class F Modifiers: protected, final.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
1 Lecture 8 Chapter 10 - Object-Oriented Programming: Polymorphism Outline Introduction Relationships Among Objects in an Inheritance Hierarchy Invoking.
 Pearson Education, Inc. All rights reserved Object-Oriented Programming: Polymorphism.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 26 - Java Object-Based Programming Outline 26.1Introduction 26.2Implementing a Time Abstract Data.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
/** Feb 1996 Cay Horstmann */ import java.util.*; import corejava.*; public class EmployeeTest { public static void main(String[]
Inheritance ndex.html ndex.htmland “Java.
Object-Oriented Programming: Polymorphism Chapter 10.
 2002 Prentice Hall. All rights reserved. Page 1 Inheritance: Object-Oriented Programming Outline 9.1 Introduction 9.2 Superclasses and Subclasses 9.3.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - Object-Oriented Programming: Polymorphism.
Object-Oriented Programming: Inheritance
Chapter 9 - Object-Oriented Programming
Object-Oriented Programming: Polymorphism
Chapter 9 Object-Oriented Programming: Inheritance
Week 6 Object-Oriented Programming (2): Polymorphism
Chapter 9 - Object-Oriented Programming: Inheritance
Chapter 20- Virtual Functions and Polymorphism
Chapter 20 - C++ Virtual Functions and Polymorphism
Chapter 19 - Inheritance Outline 19.1 Introduction
Presentation transcript:

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

Chapter 9 - 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 vice- versa –Form tree-like hierarchal structures Create a hierarchy for class Shape (next slide)

Superclasses and Subclasses 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 Shape TwoDimensionalShape ThreeDimensionalShape CircleSquareTriangleSphereCubeTetrahedron

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 Access Levels ModifierClassPackageSubclassWorld publicYYYY protectedYYYN no modifierYYNN privateYNNN The following table shows the access to members permitted by each modifier:

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 –Every class implicitly inheirts from class Object –Every constructor must call superclass constructor Called implicitly by default If explicit, must be first command –Inherits from Point –Explicitly calls superclass ( Point ) constructor Must be first statement in Circle constructor To call default superclass construcor, use super() 4public class Point { 8 public Point() 41public class Circle extends Point { // inherits from Point 54 super( a, b ); // call to superclass constructor

Relationship between Superclass Objects and Subclass Objects –Both Point and Circle override toString To call class Point 's toString in class Circle super.toString() –pointRef points to a Circle object Allowed, because Circle "is a" Point –pointRef knows it is pointing to a Circle object Calls the proper toString method Example of polymorphism - more later 83 Point pointRef, p; 84 Circle circleRef, c; 88 c = new Circle( 2.7, 120, 89 ); 95 pointRef = c; // assign Circle to pointRef 98 pointRef.toString();

Relationship between Superclass Objects and Subclass Objects –pointRef is pointing to a Circle Downcast it to a Circle reference, assign to circleRef (explicit cast) –Operator instanceof Returns true if object to which p points "is a" Circle In this case, returns false 102 circleRef = (Circle) pointRef; 87 p = new Point( 30, 50 ); 113 if ( p instanceof Circle ) {

1. Point definition 1.1 Data members 1.2 Constructors 1.3 Methods 1// Fig. 9.4: Point.java 2// Definition of class Point 3 4 4public class Point { 5 protected int x, y; // coordinates of the Point 6 7 // No-argument constructor 8 8 public Point() 9 { 10 // implicit call to superclass constructor occurs here 11 setPoint( 0, 0 ); 12 } // Constructor 15 public Point( int a, int b ) 16 { 17 // implicit call to superclass constructor occurs here 18 setPoint( a, b ); 19 } // Set x and y coordinates of Point 22 public void setPoint( int a, int b ) 23 { 24 x = a; 25 y = b; 26 } // get x coordinate 29 public int getX() { return x; } Point implicitly inherits from class Object Notice the default (no argument) constructor. Implicit call to superclass constructor.

1.4 Overridden toString method Circle Definition 1.1 extends Point 1.2 Multiple constructors // get y coordinate 32 public int getY() { return y; } // convert the point into a String representation public String toString() 36 { return "[" + x + ", " + y + "]"; } 37} 38// Fig. 9.4: Circle.java 39// Definition of class Circle 40 41public class Circle extends Point { // inherits from Point 42 protected double radius; // No-argument constructor public Circle() 46 { 47 // implicit call to superclass constructor occurs here 48 setRadius( 0 ); 49 } // Constructor 52 public Circle( double r, int a, int b ) 53 { super( a, b ); // call to superclass constructor 55 setRadius( r ); 56 } // Set radius of Circle 59 public void setRadius( double r ) 60 { radius = ( r >= 0.0 ? r : 0.0 ); } Class Point 's method toString overrides the original toString in class Object Point constructor called implicitly Point constructor called explicitly, and must be the first statement in the subclass constructor

1.3 Overridden toString method // Get radius of Circle 63 public double getRadius() { return radius; } // Calculate area of Circle 66 public double area() { return Math.PI * radius * radius; } // convert the Circle to a String 69 public String toString() 70 { 71 return "Center = " + "[" + x + ", " + y + "]" + 72 "; Radius = " + radius; 73 } 74}

1. Initialize objects 2. Refer to a subclass object with a superclass reference 2.1 toString output = "Point p: " + p.toString() + 91 "\nCircle c: " + c.toString(); // use the "is a" relationship to refer to a Circle 94 // with a Point reference pointRef = c; // assign Circle to pointRef output += "\n\nCircle c (via pointRef): " pointRef.toString(); 75// Fig. 9.4: Test.java 76// Demonstrating the "is a" relationship 77import java.text.DecimalFormat; 78import javax.swing.JOptionPane; 79 80public class InheritanceTest { 81 public static void main( String args[] ) 82 { 83 Point pointRef, p; 84 Circle circleRef, c; 85 String output; p = new Point( 30, 50 ); 88 c = new Circle( 2.7, 120, 89 ); Allowed because a subclass object "is a" superclass object The computer knows that pointRef is actually pointing to a Circle object, so it calls method toString of class Circle. This is an example of polymorphism, more later.

2.2 Downcast 2.3 toString 2.4 area 3. if statement 117 else 118 output += "\n\np does not refer to a Circle"; JOptionPane.showMessageDialog( null, output, 121 "Demonstrating the \"is a\" relationship", 122 JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); 125 } 126} // Use downcasting (casting a superclass reference to a 101 // subclass data type) to assign pointRef to circleRef circleRef = (Circle) pointRef; output += "\n\nCircle c (via circleRef): " circleRef.toString(); DecimalFormat precision2 = new DecimalFormat( "0.00" ); 108 output += "\nArea of c (via circleRef): " precision2.format( circleRef.area() ); // Attempt to refer to Point object 112 // with Circle reference if ( p instanceof Circle ) { 114 circleRef = (Circle) p; // line 40 in Test.java 115 output += "\n\ncast successful"; 116 } Downcast pointRef (which is really pointing to a Circle ) to a Circle, and assign it to circleRef 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. Class Point 1.1 Constructors 1.2 Finalizer ( protected ) 1// Fig. 9.5: Point.java 2// Definition of class Point 3public class Point extends Object { 4 protected int x, y; // coordinates of the Point 5 6 // no-argument constructor 7 public Point() 8 { 9 x = 0; 10 y = 0; 11 System.out.println( "Point constructor: " + this ); 12 } // constructor 15 public Point( int a, int b ) 16 { 17 x = a; 18 y = b; 19 System.out.println( "Point constructor: " + this ); 20 } // finalizer protected void finalize() 24 { 25 System.out.println( "Point finalizer: " + this ); 26 } // convert the point into a String representation 29 public String toString() 30 { return "[" + x + ", " + y + "]"; } 31} Only subclass may access protected methods.

1. Class Circle ( extends Point ) 1.1 Constructors 1.2 Finalizer 32// Fig. 9.5: Circle.java 33// Definition of class Circle 34public class Circle extends Point { // inherits from Point 35 protected double radius; // 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 } // 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 } // finalizer protected void finalize() 55 { 56 System.out.println( "Circle finalizer: " + this ); 57 super.finalize(); // call superclass finalize method 58 } 59 Circle finalizer calls superclass finalizer (in Point ).

1. Class Test 2. main 2.1 Initialize objects 2.2 System.gc 60 // convert the Circle to a String61 public String toString() 62 { 63 return "Center = " + super.toString() + 64 "; Radius = " + radius; 65 } 66} 67// Fig. 9.5: Test.java 68// Demonstrate when superclass and subclass 69// constructors and finalizers are called. 70public class Test { 71 public static void main( String args[] ) 72 { 73 Circle circle1, circle2; circle1 = new Circle( 4.5, 72, 29 ); 76 circle2 = new Circle( 10, 5, 5 ); circle1 = null; // mark for garbage collection 79 circle2 = null; // mark for garbage collection System.gc(); // call the garbage collector 82 } 83} Mark objects for garbage collection by setting them to null. Call garbage collector ( static method gc of class System ).

Program Output 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

Implicit Subclass-Object-to-Superclass- Object 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; //Wrong! Employee “has a” Birthdate; //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. Class Point 1.1 Instance variables 2. Constructors 2.1 Methods 1// Fig. 9.6: Point.java 2// Definition of class Point 3package com.deitel.jhtp3.ch09; 4 5public class Point { 6 protected int x, y; // coordinates of the Point 7 8 // no-argument constructor 9 public Point() { setPoint( 0, 0 ); } // constructor 12 public Point( int a, int b ) { setPoint( a, b ); } // Set x and y coordinates of Point 15 public void setPoint( int a, int b ) 16 { 17 x = a; 18 y = b; 19 } // get x coordinate 22 public int getX() { return x; } // get y coordinate 25 public int getY() { return y; } // convert the point into a String representation 28 public String toString() 29 { return "[" + x + ", " + y + "]"; } 30}

1. Class Circle ( extends Point ) 1.1 Instance variable 2. Constructors 2.1 Methods 1// Fig. 9.7: Circle.java 2// Definition of class Circle 3package com.deitel.jhtp3.ch09; 4 5public class Circle extends Point { // inherits from Point 6 protected double radius; 7 8 // no-argument constructor 9 public Circle() 10 { 11 // implicit call to superclass constructor 12 setRadius( 0 ); 13 } // Constructor 16 public Circle( double r, int a, int b ) 17 { 18 super( a, b ); // call the superclass constructor 19 setRadius( r ); 20 } // Set radius of Circle 23 public void setRadius( double r ) 24 { radius = ( r >= 0.0 ? r : 0.0 ); } // Get radius of Circle 27 public double getRadius() { return radius; } // Calculate area of Circle 30 public double area() 31 { return Math.PI * radius * radius; }

2.1 Methods // convert the Circle to a String 34 public String toString() 35 { 36 return "Center = " + super.toString() + 37 "; Radius = " + radius; 38 } 39}

1. Class Cylinder ( extends Circle ) 1.1 Instance variable 2. Constructors 2.1 Methods 1// Fig. 9.8: Cylinder.java 2// Definition of class Cylinder 3package com.deitel.jhtp3.ch09; 4 5public class Cylinder extends Circle { 6 protected double height; // height of Cylinder 7 8 // No-argument constructor 9 public Cylinder() 10 { 11 // implicit call to superclass constructor here 12 setHeight( 0 ); 13 } // constructor 16 public Cylinder( double h, double r, int a, int b ) 17 { 18 super( r, a, b ); 19 setHeight( h ); 20 } // Set height of Cylinder 23 public void setHeight( double h ) 24 { height = ( h >= 0 ? h : 0 ); } // Get height of Cylinder 27 public double getHeight() { return height; } 28

2.1 Methods Class Test 2. main 2.1 Initialize object 29 // Calculate area of Cylinder (i.e., surface area) 30 public double area() 31 { 32 return 2 * super.area() * Math.PI * radius * height; 34 } // Calculate volume of Cylinder 37 public double volume() { return super.area() * height; } // Convert the Cylinder to a String 40 public String toString() 41 { 42 return super.toString() + "; Height = " + height; 43 } 44} 45// Fig. 9.8: Test.java 46// Application to test class Cylinder 47import javax.swing.JOptionPane; 48import java.text.DecimalFormat; 49import com.deitel.jhtp3.ch09.Cylinder; 50 51public 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.2 Method calls 2.3 Set methods 2.4 Display changes 2.5 area and volume 58 output = "X coordinate is " + c.getX() + 59 "\nY coordinate is " + c.getY() + 60 "\nRadius is " + c.getRadius() + 61 "\nHeight is " + c.getHeight(); c.setHeight( 10 ); 64 c.setRadius( 4.25 ); 65 c.setPoint( 2, 2 ); 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() ); JOptionPane.showMessageDialog( null, output, 74 "Demonstrating Class Cylinder", 75 JOptionPane.INFORMATION_MESSAGE ); 76 System.exit( 0 ); 77 } 78}

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 –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. Class Employee ( abstract base class) 1.1 Instance variables 1.2 Methods 1.3 earnings ( abstract method) 1// Fig. 9.9: Employee.java 2// Abstract base class Employee 3 4 4public abstract class Employee { 5 private String firstName; 6 private String lastName; 7 8 // Constructor 9 public Employee( String first, String last ) 10 { 11 firstName = first; 12 lastName = last; 13 } // Return the first name 16 public String getFirstName() { return firstName; } // Return the last name 19 public String getLastName() { return lastName; } public String toString() 22 { return firstName + ' ' + lastName; } // Abstract method that must be implemented for each 25 // derived class of Employee from which objects 26 // are instantiated public abstract double earnings(); 28} Class Employee declared abstract, so no Employee objects can be created. Employee can still have a constructor, used by its derived classes. abstract methods must be defined in concrete subclasses.

1. Class Boss ( extends Employee ) 1.1 Instance variable 1.2 Define earnings (required) 1.3 Override toString 29// Fig. 9.9: Boss.java 30// Boss class derived from Employee 31 32public final class Boss extends Employee { 33 private double weeklySalary; // Constructor for class Boss 36 public Boss( String first, String last, double s) 37 { 38 super( first, last ); // call superclass constructor 39 setWeeklySalary( s ); 40 } // Set the Boss's salary 43 public void setWeeklySalary( double s ) 44 { weeklySalary = ( s > 0 ? s : 0 ); } // Get the Boss's pay public double earnings() { return weeklySalary; } // Print the Boss's name 50 public String toString() 51 { 52 return "Boss: " + super.toString(); 53 } 54} Implementing earnings is required because it was declared abstract and Boss is a concrete class.

1. Class CommissionWorker ( extends Employee ) 1.1 Instance variables 1.2 Constructor 55// Fig. 9.9: CommissionWorker.java 56// CommissionWorker class derived from Employee 57 58public 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 // 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 } // Set CommissionWorker's weekly base salary 74 public void setSalary( double s ) 75 { salary = ( s > 0 ? s : 0 ); } // Set CommissionWorker's commission 78 public void setCommission( double c ) 79 { commission = ( c > 0 ? c : 0 ); } // Set CommissionWorker's quantity sold 82 public void setQuantity( int q ) 83 { quantity = ( q > 0 ? q : 0 ); } 84

1.3 Define earnings (required) 1.4 Override toString Class PieceWorker ( extends Employee ) 1.1 Constructor 85 // Determine CommissionWorker's earnings 86 public double earnings() 87 { return salary + commission * quantity; } // 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 98public final class PieceWorker extends Employee { 99 private double wagePerPiece; // wage per piece output 100 private int quantity; // output for week // 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 } // Set the wage 112 public void setWage( double w ) 113 { wagePerPiece = ( w > 0 ? w : 0 ); } 114

1.2 Define earnings (required) 1.3 Override toString Class HourlyWorker ( extends Employee ) 1.1 Constructor 115// Set the number of items output 116 public void setQuantity( int q ) 117 { quantity = ( q > 0 ? q : 0 ); } // Determine the PieceWorker's earnings 120 public double earnings() 121 { return quantity * wagePerPiece; } public String toString() 124 { 125 return "Piece worker: " + super.toString(); 126 } 127} 128// Fig. 9.9: HourlyWorker.java 129// Definition of class HourlyWorker public final class HourlyWorker extends Employee { 132 private double wage; // wage per hour 133 private double hours; // hours worked for week // 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 Class Test 1.1 Employee reference 144 // Set the wage 145 public void setWage( double w ) 146 { wage = ( w > 0 ? w : 0 ); } // Set the hours worked 149 public void setHours( double h ) 150 { hours = ( h >= 0 && h < 168 ? h : 0 ); } // Get the HourlyWorker's pay 153 public double earnings() { return wage * hours; } public String toString() 156 { 157 return "Hourly worker: " + super.toString(); 158 } 159} 160// Fig. 9.9: Test.java 161// Driver for Employee hierarchy 162import javax.swing.JOptionPane; 163import java.text.DecimalFormat; public class Test { 166 public static void main( String args[] ) 167 { Employee ref; // superclass reference 169 String output = ""; 170 References to abstract classes are allowed.

1.2 Initialize subclass objects 2. Method calls through Employee reference 171 Boss b = new Boss( "John", "Smith", ); 172 CommissionWorker c = 173 new CommissionWorker( "Sue", "Jones", , 3.0, 150); 175 PieceWorker p = 176 new PieceWorker( "Bob", "Lewis", 2.5, 200 ); 177 HourlyWorker h = 178 new HourlyWorker( "Karen", "Price", 13.75, 40 ); DecimalFormat precision2 = new DecimalFormat( "0.00" ); ref = b; // Employee reference to a Boss 183 output += ref.toString() + " earned $" precision2.format( ref.earnings() ) + "\n" b.toString() + " earned $" precision2.format( b.earnings() ) + "\n"; ref = c; // Employee reference to a CommissionWorker 189 output += ref.toString() + " earned $" precision2.format( ref.earnings() ) + "\n" c.toString() + " earned $" precision2.format( c.earnings() ) + "\n"; ref = p; // Employee reference to a PieceWorker 195 output += ref.toString() + " earned $" precision2.format( ref.earnings() ) + "\n" p.toString() + " earned $" precision2.format( p.earnings() ) + "\n"; 199 Employee reference ref points to Boss object. Through polymorphism, the appropriate Boss versions of toString and earnings are called. To check, they are called through the Boss object as well.

2. Method calls through Employee reference Program Output 200 ref = h; // Employee reference to an HourlyWorker 201 output += ref.toString() + " earned $" precision2.format( ref.earnings() ) + "\n" h.toString() + " earned $" precision2.format( h.earnings() ) + "\n"; JOptionPane.showMessageDialog( null, output, 207 "Demonstrating Polymorphism", 208 JOptionPane.INFORMATION_MESSAGE ); 209 System.exit( 0 ); 210 } 211}

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() + ": " arrayOfShapes[ i ].toString() +

1. Class Shape ( abstract superclass) 1.1 getName ( abstract method) Class Point ( extends Shape ) 1.1 protected data members 1.2 Constructors 1.3 New methods 1// Fig. 9.10: Shape.java 2// Definition of abstract base class Shape 3 4public abstract class Shape extends Object { 5 5 public double area() { return 0.0; } 6 public double volume() { return 0.0; } 7 public abstract String getName(); 8}8} 9// Fig. 9.10: Point.java 10// Definition of class Point 11 12public class Point extends Shape { 13 protected int x, y; // coordinates of the Point // no-argument constructor 16 public Point() { setPoint( 0, 0 ); } // constructor 19 public Point( int a, int b ) { setPoint( a, b ); } // Set x and y coordinates of Point 22 public void setPoint( int a, int b ) 23 { 24 x = a; 25 y = b; 26 } // get x coordinate 29 public int getX() { return x; } 30 Methds area and volume are defined. They will be overridden in the subclasses when necessary.

1.4 Overridden method getName (required) Class Circle ( extends Point ) 1.1 protected data member 1.2 Constructors 1.3 New methods 31 // get y coordinate 32 public int getY() { return y; } // convert the point into a String representation 35 public String toString() 36 { return "[" + x + ", " + y + "]"; } // return the class name public String getName() { return "Point"; } 40} 41// Fig. 9.10: Circle.java 42// Definition of class Circle 43 44public class Circle extends Point { // inherits from Point 45 protected double radius; // no-argument constructor 48 public Circle() 49 { 50 // implicit call to superclass constructor here 51 setRadius( 0 ); 52 } // Constructor 55 public Circle( double r, int a, int b ) 56 { 57 super( a, b ); // call the superclass constructor 58 setRadius( r ); 59 } 60 abstract method getName must be overridden in a concrete subclass.

1.4 Overridden method area 1.5 Overridden method toString 1.6 Overridden method getName (required) Class Cylinder ( extends Circle ) 1.1 protected data member 1.2 Constructors 61 // Set radius of Circle 62 public void setRadius( double r ) 63 { radius = ( r >= 0 ? r : 0 ); } // Get radius of Circle 66 public double getRadius() { return radius; } // Calculate area of Circle public double area() { return Math.PI * radius * radius; } // convert the Circle to a String 72 public String toString() 73 { return "Center = " + super.toString() + 74 "; Radius = " + radius; } // return the class name 77 public String getName() { return "Circle"; } 78} 79// Fig. 9.10: Cylinder.java 80// Definition of class Cylinder 81 82public class Cylinder extends Circle { 83 protected double height; // height of Cylinder // no-argument constructor 86 public Cylinder() 87 { 88 // implicit call to superclass constructor here 89 setHeight( 0 ); 90 } Circle overrides method area, inherited from Shape. Point did not override area, and has the default implementation (returns 0 ).

1.2 Constructors 1.3 New methods 1.4 Overridden method area 1.5 Overridden method toString 1.6 Overridden method getName // constructor 93 public Cylinder( double h, double r, int a, int b ) 94 { 95 super( r, a, b ); // call superclass constructor 96 setHeight( h ); 97 } // Set height of Cylinder 100 public void setHeight( double h ) 101 { height = ( h >= 0 ? h : 0 ); } // Get height of Cylinder 104 public double getHeight() { return height; } // Calculate area of Cylinder (i.e., surface area) 107 public double area() 108 { 109 return 2 * super.area() * Math.PI * radius * height; 111 } // Calculate volume of Cylinder 114 public double volume() { return super.area() * height; } // Convert a Cylinder to a String 117 public String toString() 118 { return super.toString() + "; Height = " + height; } // Return the class name 121 public String getName() { return "Cylinder"; } 122}

Class Test (driver) 1. import 1.1 Initialize objects 1.2 Create array of Shape references 1.3 Initialize array 2. Call methods using subclass references 123// Fig. 9.10: Test.java 124// Driver for point, circle, cylinder hierarchy 125import javax.swing.JOptionPane; 126import java.text.DecimalFormat; 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 ); Shape arrayOfShapes[]; arrayOfShapes = new Shape[ 3 ]; // aim arrayOfShapes[0] at subclass Point object arrayOfShapes[ 0 ] = point; // aim arrayOfShapes[1] at subclass Circle object 143 arrayOfShapes[ 1 ] = circle; // aim arrayOfShapes[2] at subclass Cylinder object 146 arrayOfShapes[ 2 ] = cylinder; String output = 149 point.getName() + ": " + point.toString() + "\n" circle.getName() + ": " + circle.toString() + "\n" cylinder.getName() + ": " + cylinder.toString(); Create an array of Shape references. Point the Shape references towards subclass objects.

2.1 Call methods using Shape references DecimalFormat precision2 = new DecimalFormat( "0.00" ); // 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" arrayOfShapes[ i ].getName() + ": " arrayOfShapes[ i ].toString() "\nArea = " precision2.format( arrayOfShapes[ i ].area() ) "\nVolume = " precision2.format( arrayOfShapes[ i ].volume() ); 165 } JOptionPane.showMessageDialog( null, output, 168 "Demonstrating Polymorphism", 169 JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); 172 } 173} Call methods using superclass references. Appropriate method called because of polymorphism.

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. Shape interface 1.1 abstract methods Class Point ( implements Shape) 1 1// Fig. 9.11: Shape.java 2// Definition of interface Shape 3 4public interface Shape { 5 public abstract double area(); 6 public abstract double volume(); 7 public abstract String getName(); 8}8} 9// Fig. 9.11: Point.java 10// Definition of class Point public class Point extends Object implements Shape { 13 protected int x, y; // coordinates of the Point // no-argument constructor 16 public Point() { setPoint( 0, 0 ); } // constructor 19 public Point( int a, int b ) { setPoint( a, b ); } // Set x and y coordinates of Point 22 public void setPoint( int a, int b ) 23 { 24 x = a; 25 y = b; 26 } 27 Interface Shape is in its own file, Shape.java Because Point implements interface Shape, it is required to define the abstract methods in Shape.

1.1 Define method area (required) 1.2 Define method volume (required) 1.3 Define method getName (required) Class Circle and Cylinder defined as before 28 // get x coordinate 29 public int getX() { return x; } // get y coordinate 32 public int getY() { return y; } // convert the point into a String representation 35 public String toString() 36 { return "[" + x + ", " + y + "]"; } // return the area public double area() { return 0.0; } // return the volume 42 public double volume() { return 0.0; } // return the class name 45 public String getName() { return "Point"; } 46} Point required to define the abstract methods of the interface it implements.

Use same class Test as before 123// Fig. 9.11: Test.java 124// Driver for point, circle, cylinder hierarchy 125import javax.swing.JOptionPane; 126import java.text.DecimalFormat; 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 ); Shape arrayOfShapes[]; arrayOfShapes = new Shape[ 3 ]; // aim arrayOfShapes[0] at subclass Point object 140 arrayOfShapes[ 0 ] = point; // aim arrayOfShapes[1] at subclass Circle object 143 arrayOfShapes[ 1 ] = circle; // aim arrayOfShapes[2] at subclass Cylinder object 146 arrayOfShapes[ 2 ] = cylinder; String output = 149 point.getName() + ": " + point.toString() + "\n" circle.getName() + ": " + circle.toString() + "\n" cylinder.getName() + ": " + cylinder.toString();

Use same class Test as before DecimalFormat precision2 = new DecimalFormat( "0.00" ); // 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" arrayOfShapes[ i ].getName() + ": " arrayOfShapes[ i ].toString() "\nArea = " precision2.format( arrayOfShapes[ i ].area() ) "\nVolume = " precision2.format( arrayOfShapes[ i ].volume() ); 165 } JOptionPane.showMessageDialog( null, output, 168 "Demonstrating Polymorphism", 169 JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); 172 } 173}

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) 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) 64public class TimeTestWindow extends JFrame { 117 TimeTestWindow window = new TimeTestWindow();

Inner Class Definitions Window Minimize, maximize, and close Title bar

Inner Class Definitions –Event handling –Some class must implement interface ActionListener Must define method actionPerformed Class that implements ActionListener "is an" ActionListener –Method addActionListener Takes object of type ActionListener Pass it instance of the class that implements ActionListener ("is a" relationship) 123 // INNER CLASS DEFINITION FOR EVENT HANDLING 124 private class ActionEventHandler implements ActionListener { 79 // create an instance of the inner class 80 ActionEventHandler handler = new ActionEventHandler(); 85 hourField.addActionListener( handler );

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. Time class 1.2 Data members 1.3 Constructors 1.4 Methods 1// Fig. 9.12: Time.java 2// Time class definition 3import java.text.DecimalFormat; // used for number formatting 4 5// This class maintains the time in 24-hour format 6public class Time extends Object { 7 private int hour; // private int minute; // private int second; // // Time constructor initializes each instance variable 12 // to zero. Ensures that Time object starts in a 13 // consistent state. 14 public Time() { setTime( 0, 0, 0 ); } // Set a new time value using universal time. Perform 17 // validity checks on the data. Set invalid values to zero. 18 public void setTime( int h, int m, int s ) 19 { 20 setHour( h ); // set the hour 21 setMinute( m ); // set the minute 22 setSecond( s ); // set the second 23 } // set the hour 26 public void setHour( int h ) 27 { hour = ( ( h >= 0 && h < 24 ) ? h : 0 ); } // set the minute 30 public void setMinute( int m ) 31 { minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); }

1.4 Methods // set the second 34 public void setSecond( int s ) 35 { second = ( ( s >= 0 && s < 60 ) ? s : 0 ); } // get the hour 38 public int getHour() { return hour; } // get the minute 41 public int getMinute() { return minute; } // get the second 44 public int getSecond() { return second; } // Convert to String in standard-time format 47 public String toString() 48 { 49 DecimalFormat twoDigits = new DecimalFormat( "00" ); return ( ( getHour() == 12 || getHour() == 0 ) ? : getHour() % 12 ) + ":" + 53 twoDigits.format( getMinute() ) + ":" + 54 twoDigits.format( getSecond() ) + 55 ( getHour() < 12 ? " AM" : " PM" ); 56 } 57}

1. import 1.1 Class TimeTestWindow ( extends JFrame ) 1.2 Create GUI components in constructor 1.3 Create instance of class that implements ActionListener 1.4 addActionListener 58// Fig. 9.12: TimeTestWindow.java 59// Demonstrating the Time class set and get methods 60import java.awt.*; 61import java.awt.event.*; 62import javax.swing.*; 63 64public class TimeTestWindow extends JFrame { 65 private Time t; 66 private JLabel hourLabel, minuteLabel, secondLabel; 67 private JTextField hourField, minuteField, 68 secondField, display; 69 private JButton exitButton; public TimeTestWindow() 72 { super( "Inner Class Demonstration" ); t = new Time(); Container c = getContentPane(); // create an instance of the inner class 80 ActionEventHandler handler = new ActionEventHandler(); c.setLayout( new FlowLayout() ); 83 hourLabel = new JLabel( "Set Hour" ); 84 hourField = new JTextField( 10 ); hourField.addActionListener( handler ); 86 c.add( hourLabel ); 87 c.add( hourField ); 88 Call to JFrame constructor sets title bar of window. Object of inner class ActionEventHandler passed as an argument to addActionListener Set up all GUI components in constructor. In main, create a TimeTestWindow object, which runs the constructor.

1.5 Create GUI components 2. Methods 3. main 3.1 Create object 89 minuteLabel = new JLabel( "Set minute" ); 90 minuteField = new JTextField( 10 ); 91 minuteField.addActionListener( handler ); 92 c.add( minuteLabel ); 93 c.add( minuteField ); secondLabel = new JLabel( "Set Second" ); 96 secondField = new JTextField( 10 ); 97 secondField.addActionListener( handler ); 98 c.add( secondLabel ); 99 c.add( secondField ); display = new JTextField( 30 ); 102 display.setEditable( false ); 103 c.add( display ); exitButton = new JButton( "Exit" ); 106 exitButton.addActionListener( handler ); 107 c.add( exitButton ); 108 } public void displayTime() 111 { 112 display.setText( "The time is: " + t ); 113 } public static void main( String args[] ) 116 { TimeTestWindow window = new TimeTestWindow(); Create TimeTestWindow object.

4. Inner class ActionEventHandler implements ActionListener window.setSize( 400, 140 ); 120 window.show(); 121 } // INNER CLASS DEFINITION FOR EVENT HANDLING private class ActionEventHandler implements ActionListener { 127 if ( e.getSource() == exitButton ) 128 System.exit( 0 ); // terminate the application 129 else if ( e.getSource() == hourField ) { 130 t.setHour( 131 Integer.parseInt( e.getActionCommand() ) ); 132 hourField.setText( "" ); 133 } 134 else if ( e.getSource() == minuteField ) { 135 t.setMinute( 136 Integer.parseInt( e.getActionCommand() ) ); 137 minuteField.setText( "" ); 138 } 139 else if ( e.getSource() == secondField ) { 140 t.setSecond( 141 Integer.parseInt( e.getActionCommand() ) ); 142 secondField.setText( "" ); 143 } displayTime(); 146 } 147 } 148} 126 { 125 public void actionPerformed( ActionEvent e ) Use a named inner class as the event handler. Class implements interface ActionListener, and must define actionPerformed.

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 –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 24 hourField.addActionListener( 25 new ActionListener() { // anonymous inner class 26 public void actionPerformed( ActionEvent e ) 27 { 28 t.setHour( 29 Integer.parseInt( e.getActionCommand() ) ); 30 hourField.setText( "" ); 31 displayTime(); 32 } 33 } 34 );

Inner Class Definitions –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 82 TimeTestWindow window = new TimeTestWindow(); 84 window.addWindowListener( 85 new WindowAdapter() { 86 public void windowClosing( WindowEvent e ) 87 { 88 System.exit( 0 ); 89 } 90 } 91 );

Inner Class Definitions –new WindowAdapter() Begins anonymous inner class that extends WindowAdapter Similar to: public class myHandler extends WindowAdapter { 82 TimeTestWindow window = new TimeTestWindow(); 84 window.addWindowListener( 85 new WindowAdapter() { 86 public void windowClosing( WindowEvent e ) 87 { 88 System.exit( 0 ); 89 } 90 } 91 );

1. import 1.1 Class TimeTestWindow (extends JFrame) 1.2 Constructor 1.3 Initialze GUI 2. Event handler ( anonymous inner class) 1// Fig. 9.13: TimeTestWindow.java 2// Demonstrating the Time class set and get methods 3import java.awt.*; 4import java.awt.event.*; 5import javax.swing.*; 6 7public class TimeTestWindow extends JFrame { 8 private Time t; 9 private JLabel hourLabel, minuteLabel, secondLabel; 10 private JTextField hourField, minuteField, 11 secondField, display; public TimeTestWindow() 14 { 15 super( "Inner Class Demonstration" ); t = new Time(); Container c = getContentPane(); c.setLayout( new FlowLayout() ); 22 hourLabel = new JLabel( "Set Hour" ); 23 hourField = new JTextField( 10 ); 24 hourField.addActionListener( new ActionListener() { // anonymous inner class 26 public void actionPerformed( ActionEvent e ) 27 { 28 t.setHour( 29 Integer.parseInt( e.getActionCommand() ) ); An object of an anonymous inner class is used as the event handler.

2. Event handler ( anonymous inner class) 30 hourField.setText( "" ); 31 displayTime(); 32 } 33 } 34 ); 35 c.add( hourLabel ); 36 c.add( hourField ); minuteLabel = new JLabel( "Set minute" ); 39 minuteField = new JTextField( 10 ); 40 minuteField.addActionListener( new ActionListener() { // anonymous inner class 42 public void actionPerformed( ActionEvent e ) 43 { 44 t.setMinute( 45 Integer.parseInt( e.getActionCommand() ) ); 46 minuteField.setText( "" ); 47 displayTime(); 48 } 49 } 50 ); 51 c.add( minuteLabel ); 52 c.add( minuteField ); secondLabel = new JLabel( "Set Second" ); 55 secondField = new JTextField( 10 ); 56 secondField.addActionListener( 57 new ActionListener() { // anonymous inner class 58 public void actionPerformed( ActionEvent e ) Each button has a separate inner class as an event handler.

3. main 3.1 Create TimeTestWindow object 3.2 addWindowListener 59 {60 t.setSecond( 61 Integer.parseInt( e.getActionCommand() ) ); 62 secondField.setText( "" ); 63 displayTime(); 64 } 65 } 66 ); 67 c.add( secondLabel ); 68 c.add( secondField ); display = new JTextField( 30 ); 71 display.setEditable( false ); 72 c.add( display ); 73 } public void displayTime() 76 { 77 display.setText( "The time is: " + t ); 78 } public static void main( String args[] ) 81 { 82 TimeTestWindow window = new TimeTestWindow(); window.addWindowListener( 85 new WindowAdapter() { Use an anonymous inner class to handle window events.

Program Output 86 public void windowClosing( WindowEvent e ) 87 { 88 System.exit( 0 ); 89 } 90 } 91 ); window.setSize( 400, 120 ); 94 window.show(); 95 } 96}

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. 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