Title: Chapter 2: Using Objects
1Chapter 7
Inheritance
2Inheritance
- A fundamental object-oriented technique.
- Inheritance enhances software design and promotes
software reuse - deriving new classes
- creating class hierarchies
- the protected modifier
- polymorphism via inheritance
- inheritance used in graphical user interfaces
3Inheritance
- Inheritance allows a software developer to derive
a new class from an existing one - The existing class is called the parent class, or
superclass, or base class - The derived class is called the child class or
subclass. - As the name implies, the child inherits
characteristics of the parent - That is, the child class inherits the methods and
data defined for the parent class
4Inheritance
- Inheritance relationships are often shown
graphically in a class diagram, with the arrow
pointing to the parent class
Inheritance should create an is-a relationship,
meaning the child is a more specific version of
the parent
5Deriving Subclasses
- In Java, we use the reserved word extends to
establish an inheritance relationship - class Car extends Vehicle
-
- // class contents
-
6// Represents a book. //
class Book
protected int pages 1500
//------------------------------------------------
---------------- // Prints a message
concerning the pages of this book.
//------------------------------------------------
---------------- public void pageMessage ()
System.out.println ("Number of pages "
pages)
7// Represents a dictionary, which is a
book. //
class Dictionary
extends Book private int definitions
52500 //-------------------------------------
---------------------------- // Prints a
message using both local and inherited values.
//------------------------------------------------
----------------- public void
definitionMessage ()
System.out.println ("Number of definitions "
definitions) System.out.println
("Definitions per page " definitions/pages)
8// Demonstrates the use of an inherited
method. //
class Words
//------------------------------------------------
----------------- // Instantiates a derived
class and invokes its inherited and // local
methods. //------------------------------------
----------------------------- public static
void main (String args) Dictionary
webster new Dictionary ()
webster.pageMessage() webster.definitionMes
sage()
9The super Reference
- Constructors are not inherited, even though they
have public visibility - Yet we often want to use the parent's constructor
to set up the "parent's part" of the object - The super reference can be used to refer to the
parent class, and is often used to invoke the
parent's constructor
10The super Reference
- Overridding methods
- Subclass can redefine superclass method
- When method mentioned in subclass, the subclass
version used - Access original superclass method with
super.methodName - To invoke superclass constructor
explicitlysuper() //can pass arguments if
needed - If called explicitly, must be first statement
11// Represents a book. //
class Book2 protected
int pages //----------------------------------
------------------------------ // Sets up the
book with the specified number of pages.
//------------------------------------------------
---------------- public Book2 (int pages)
this.pages pages
//------------------------------------------------
---------------- // Prints a message
concerning the pages of this book.
//------------------------------------------------
---------------- public void pageMessage ()
System.out.println ("Number of pages "
pages)
12// Represents a dictionary, which is a
book. //
class Dictionary2
extends Book2 private int definitions
//------------------------------------------------
----------------- // Sets up the dictionary
with the specified number of pages //
(maintained by the Book parent class) and
defintions. //---------------------------------
-------------------------------- public
Dictionary2 (int pages, int definitions)
super (pages) // Calls
supers constructor. this.definitions
definitions //---------------------------
-------------------------------------- //
Prints a message using both local and inherited
values. //-------------------------------------
---------------------------- public void
definitionMessage ()
System.out.println ("Number of definitions "
definitions) System.out.println
("Definitions per page " definitions/pages)
13// Demonstrates the use of the super
reference. //
class Words2
//-----------------------------------------------
------------------ // Instantiates a derived
class and invokes its inherited and // local
methods. //------------------------------------
----------------------------- public static
void main (String args) Dictionary2
webster new Dictionary2 (1500, 52500)
webster.pageMessage() webster.definitionMes
sage()
14Controlling Inheritance
- Visibility modifiers determine which class
members get inherited and which do not - Variables and methods declared with public
visibility are inherited, and those with private
visibility are not - But public variables violate our goal of
encapsulation - There is a third visibility modifier that helps
in inheritance situations protected
15protected 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
16Single vs. Multiple Inheritance
- Java supports single inheritance, meaning that a
derived class can have only one parent class - Multiple inheritance allows a class to be derived
from two or more classes, inheriting the members
of all parents - Collisions, such as the same variable name in two
parents, have to be resolved - In most cases, the use of interfaces gives us the
best aspects of multiple inheritance without the
overhead
17Overriding Methods
- A child class can override the definition of an
inherited method in favor of its own - That is, a child can redefine a method that it
inherits from its parent - The new method must have the same signature as
the parent's method, but can have different code
in the body - The type of the object executing the method
determines which version of the method is invoked
18// Represents a stray thought. //
class Thought //------------------------
----------------------------------------- //
Prints a message. //---------------------------
-------------------------------------- public
void message() System.out.println ("I
feel like I'm diagonally parked in a "
"parallel universe.")
System.out.println()
19// Represents a hopefully helpful piece of
advice. //
class Advice
extends Thought //---------------------------
-------------------------------------- //
Prints a message. This method overrides the
parent's version. // It also invokes the
parent's version explicitly using super.
//------------------------------------------------
----------------- public void message() //
overiding System.out.println
("Warning Dates in calendar are closer "
"than they appear.")
System.out.println() super.message()
20// Demonstrates the use of an overridden
method. //
class Messages
//------------------------------------------------
----------------- // Instatiates two objects
a invokes the message method in each.
//------------------------------------------------
----------------- public static void main
(String args) Thought parked new
Thought() Advice dates new Advice()
parked.message () dates.message ()
// overridden
21Overriding Methods
- Note that a parent method can be explicitly
invoked using the super reference - If a method is declared with the final modifier,
it cannot be overridden - The concept of overriding can be applied to data
(called shadowing variables), there is generally
no need for it
22Overloading vs. Overriding
- Don't confuse the concepts of overloading and
overriding - Overloading deals with multiple methods in the
same class with the same name but different
signatures - Overriding deals with two methods, one in a
parent class and one in a child class, that have
the same signature - Overloading lets you define a similar operation
in different ways for different data - Overriding lets you define a similar operation in
different ways for different object types
23Class Hierarchies
A child class of one parent can be the parent of
another child, forming class hierarchies
24Class Hierarchies
- Two children of the same parent are called
siblings - Good class design puts all common features as
high in the hierarchy as is reasonable - An inherited member is continually passed down
the line - Class hierarchies often have to be extended and
modified to keep up with changing needs - There is no single class hierarchy that is
appropriate for all situations
25The Object Class
- A class called Object is defined in the java.lang
package of the Java standard class library - All classes are derived from the Object class
- If a class is not explicitly defined to be the
child of an existing class, it is assumed to be
the child of the Object class - The Object class is therefore the ultimate root
of all class hierarchies
26The Object Class
- The Object class contains a few useful methods,
which are inherited by all classes - For example, the toString method is defined in
the Object class - Every time we have defined toString, we have
actually been overriding it - The toString method in the Object class is
defined to return a string that contains the name
of the objects class and a hash value
27The Object Class
- Thats why the println method can call toString
for any object that is passed to it all objects
are guaranteed to have a toString method via
inheritance - The equals method of the Object class determines
if two references are aliases - You may choose to override equals to define
equality in some other way
28// Represents a student. //
class Student
protected String name protected int
numCourses //---------------------------------
-------------------------------- // Sets up a
student with the specified name and number of
// courses. //--------------------------------
--------------------------------- public
Student (String name, int numCourses)
this.name name this.numCourses
numCourses //----------------------------
------------------------------------- //
Returns information about this student as a
string. //-------------------------------------
---------------------------- public String
toString () String result "Student
name " name "\n" result "Number
of courses " numCourses return
result
29// Represents a graduate student, with financial
support. //
class GradStudent extends Student
private String source private double rate
//----------------------------------------------
------------------- // Sets up the gradate
student using the specified information.
//------------------------------------------------
----------------- public GradStudent (String
name, int numCourses, String source,
double rate) super (name,
numCourses) this.source source
this.rate rate
30//------------------------------------------------
----------------- // Returns a description of
this graduate student as a string.
//------------------------------------------------
----------------- public String toString ()
String result super.toString()
result "\nSupport source " source "\n"
result "Hourly pay rate " rate
return result
31// Demonstrates inheritance from the Object
class. //
class Academia //-----------------
------------------------------------------------
// Creates objects of two student types,
prints some information // about them, then
checks them for equality. //-------------------
----------------------------------------------
public static void main (String args)
Student susan new Student ("Susan", 5)
GradStudent frank new GradStudent ("Frank", 3,
"GTA", 8.75) System.out.println (susan)
System.out.println ()
System.out.println (frank)
System.out.println () if (!
susan.equals(frank)) System.out.println
("These are two different students.")
32Abstract Classes
- An abstract class is a placeholder in a class
hierarchy that represents a generic concept - An abstract class cannot be instantiated
- We use the modifier abstract on the class header
to declare a class as abstract - An abstract class often contains abstract methods
(like an interface does), though it doesnt have
to
33Abstract Classes
- The child of an abstract class must override the
abstract methods of the parent, or it too will be
considered abstract - An abstract method cannot be defined as final
(because it must be overridden) or static
(because it has no definition yet) - The use of abstract classes is a design decision
it helps us establish common elements in a class
that is too general to instantiate
34References and Inheritance
- An object reference can refer to an object of its
class, or to an object of any class related to it
by inheritance - For example, if the Holiday class is used to
derive a child class called Chanuka, then a
Holiday reference could actually be used to point
to a Chanuka object
Holiday day day new Chanuka()
35References and Inheritance
- Assigning a child object to an ancestor reference
can be performed by simple assignment (a widening
conversion). - Assigning an ancestor object to a child reference
can also be done, but it is considered to be a
narrowing conversion and must be done with a cast - The widening conversion is the most useful
- instanceof operator
- if (p instanceof Circle)
- Returns true if the object to which p points "is
a" Circle
36Relationship 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()
37Relationship 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
38Relationship between Superclass Objects and
Subclass Objects
- pointRef is pointing to a Circle
- Downcast it to a Circle reference, assign to
circleRef - Operator instanceof
- Returns true if object to which p points "is a"
Circle - In this case, returns false
39- 1. Point definition
- 1.1 Data members
- 1.2 Constructors
- 1.3 Methods
40- 1.4 Overridden toString method
- ----------------
- 1. Circle Definition
- 1.1 extends Point
- 1.2 Multiple constructors
41- 1.3 Overridden toString method
42- 1. Initialize objects
- 2. Refer to a subclass object with a superclass
reference - 2.1 toString
43- 2.2 Downcast
- 2.3 toString
- 2.4 area
- 3. if statement
44 459.9 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
46- 1. Class Point
- 1.1 Instance variables
- 2. Constructors
- 2.1 Methods
47- 1. Class Circle (extends Point)
- 1.1 Instance variable
- 2. Constructors
- 2.1 Methods
48(No Transcript)
49- 1. Class Cylinder (extends Circle)
- 1.1 Instance variable
- 2. Constructors
- 2.1 Methods
50- 2.1 Methods
- ------------
- 1. Class Test
- 2. main
- 2.1 Initialize object
51- 2.2 Method calls
- 2.3 Set methods
- 2.4 Display changes
- 2.5 area and volume
52 53Polymorphism via Inheritance
- A polymorphic reference is one which can refer to
different types of objects at different times - Inheritance can be used as a basis of
polymorphism - An object reference can refer to one object at
one time, then it can be changed to refer to
another object (related by inheritance) at
another time
54Polymorphism via Inheritance
- Suppose the Holiday class has a method called
celebrate, and the Chanuka class overrodes it - Now consider the following invocation
- day.celebrate()
- If day refers to a Holiday object, it invokes the
Holiday version of celebrate if it refers to a
Chanuka object, it invokes the Chanuka version
55Polymorphism via Inheritance
- It is the type of the object being referenced,
not the reference type, that determines which
method is invoked - Note that, if an invocation is in a loop, the
exact same line of code could execute different
methods at different times - Polymorphic references are therefore resolved at
run-time, not during compilation
56Polymorphism via Inheritance
- Consider the following class hierarchy
57Polymorphism via Inheritance
- Now consider the task of paying all employees
58// Represents a generic staff member. //
abstract class StaffMember
protected String name protected String
address protected String phone
//------------------------------------------------
----------------- // Sets up a staff member
using the specified information.
//------------------------------------------------
----------------- public StaffMember (String
name, String address, String phone)
this.name name this.address address
this.phone phone
59//------------------------------------------------
----------------- // Returns a string
including the basic employee information.
//------------------------------------------------
----------------- public String toString ()
String result "Name " name "\n"
result "Address " address "\n"
result "Phone " phone return
result //-------------------------------
---------------------------------- // Derived
classes must define the pay method for each
employee // type. //-----------------------
------------------------------------------
public abstract double pay()
60class Volunteer extends StaffMember
//------------------------------------------------
----------------- // Sets up a volunteer
using the specified information.
//------------------------------------------------
----------------- public Volunteer (String
name, String address, String phone)
super (name, address, phone)
//------------------------------------------------
----------------- // Returns a zero pay value
for this volunteer. //-------------------------
----------------------------------------
public double pay() return 0.0
61// Represents a general paid employee. //
class Employee extends
StaffMember protected String
socialSecurityNumber protected double
payRate //--------------------------------
--------------------------------- // Sets up
an employee with the specified information.
//------------------------------------------------
----------------- public Employee (String
name, String address, String phone,
String socialSecurityNumber, double
payRate) super (name, address,
phone) this.socialSecurityNumber
socialSecurityNumber this.payRate
payRate
62//------------------------------------------------
----------------- // Returns information
about an employee as a string.
//------------------------------------------------
---------------- public String toString ()
String result super.toString()
result "\nSocial Security Number "
socialSecurityNumber return result
//------------------------------------------
----------------------- // Returns the pay
rate for this employee. //---------------------
--------------------------------------------
public double pay () return payRate
63// Represents an executive staff member, who can
earn a bonus. //
class
Executive extends Employee private double
bonus //-------------------------------------
---------------------------- // Sets up an
executive with the specified information.
//------------------------------------------------
----------------- public Executive (String
name, String address, String phone,
String socialSecurityNumber, double
payRate) super (name, address, phone,
socialSecurityNumber, payRate) bonus 0
// bonus has yet to be awarded
64//------------------------------------------------
----------------- // Awards the specified
bonus to this executive. //--------------------
---------------------------------------------
public void awardBonus (double execBonus)
bonus execBonus //-----------------
------------------------------------------------
// Computes and returns the pay for an
executive, which is the // regular employee
payment plus a one-time bonus.
//------------------------------------------------
----------------- public double pay ()
double payment super.pay() bonus
bonus 0 return payment
65class Hourly extends Employee private int
hoursWorked //-------------------------------
---------------------------------- // Sets up
this hourly employee using the specified
information. //--------------------------------
--------------------------------- public
Hourly (String name, String address, String
phone, String
socialSecurityNumber, double payRate)
super (name, address, phone, socialSecurityNumber,
payRate) hoursWorked 0
//------------------------------------------------
----------------- // Adds the specified
number of hours to this employee's //
accumulated hours. //--------------------------
--------------------------------------- public
void addHours (int moreHours)
hoursWorked moreHours
66//------------------------------------------------
----------------- // Computes and returns the
pay for this hourly employee.
//------------------------------------------------
----------------- public double pay ()
double payment payRate hoursWorked
hoursWorked 0 return payment
//------------------------------------------------
----------------- // Returns information
about this hourly employee as a string.
//------------------------------------------------
----------------- public String toString ()
String result super.toString()
result "\nCurrent hours " hoursWorked
return result
67// Represents the personnel staff of a
particular business. //
class
Staff StaffMember staffList
//------------------------------------------------
----------------- // Sets up the list of
staff members. //------------------------------
----------------------------------- public
Staff () staffList new
StaffMember6 staffList0 new
Executive ("Sam", "123 Main Line",
"555-0469", "123-45-6789", 1923.07)
staffList1 new Employee ("Carla", "456 Off
Line", "555-0101", "987-65-4321",
846.15) staffList2 new Employee
("Woody", "789 Off Rocker", "555-0000",
"010-20-3040", 769.23) staffList3 new
Hourly ("Diane", "678 Fifth Ave.",
"555-0690", "958-47-3625", 8.55)
68staffList4 new Volunteer ("Norm", "987 Suds
Blvd.", "555-8374") staffList5
new Volunteer ("Cliff", "321 Duds Lane",
"555-7282") ((Executive)staffList0).aw
ardBonus (5000.00) ((Hourly)staffList3).
addHours (40) //-------------------------
---------------------------------------- //
Pays all staff members. //---------------------
--------------------------------------------
public void payday () double amount
for (int count0 count lt staffList.length
count) System.out.println
(staffListcount) amount
staffListcount.pay() // polymorphic
if (amount 0.0) System.out.println
("Thanks!") else
System.out.println ("Paid " amount)
System.out.println ("-----------------------------
------")
69// Demonstrates polymorphic processing. //
class
Firm //--------------------------------------
--------------------------- // Creates a
staff of employees for a firm and pays them.
//------------------------------------------------
----------------- public static void main
(String args) Staff personnel new
Staff() personnel.payday()
70Polymorphism
- 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
71switch 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
72Dynamic 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
73final 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
74New 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
75Indirect Access
- An inherited member can be referenced directly by
name in the child class, as if it were declared
in the child class - But even if a method or variable is not inherited
by a child, it can still be accessed indirectly
through parent methods
76// Demonstrates indirect referencing through
inheritance. //
class FoodItem final
private int CALORIES_PER_GRAM 9 private int
fatGrams protected int servings
//------------------------------------------------
----------------- // Sets up this food item
with the specified number of fat grams // and
number of servings. //-------------------------
----------------------------------------
public FoodItem (int fatGrams, int servings)
this.fatGrams fatGrams
this.servings servings
77//------------------------------------------------
----------------- // Computes and returns the
number of calories in this food item // due
to fat. //-------------------------------------
---------------------------- private int
calories () return fatGrams
CALORIES_PER_GRAM //--------------------
---------------------------------------------
// Computes and returns the number of fat
calories per serving. //-----------------------
------------------------------------------
public int caloriesPerServing ()
return (calories() / servings)
78// Demonstrates indirect referencing through
inheritance. //
class Pizza extends FoodItem
//------------------------------------------------
----------------- // Sets up a pizza with the
specified amount of fat assumes // eight
servings. //-----------------------------------
------------------------------ public Pizza
(int fatGrams) super (fatGrams, 8)
79// Demonstrates indirect referencing through
inheritance. //
class
FoodAnalysis //------------------------------
----------------------------------- //
Instantiates a Pizza object and prints its
calories per // serving.
//------------------------------------------------
----------------- public static void main
(String args) Pizza special new
Pizza (275) System.out.println ("Calories
per serving "
special.caloriesPerServing())
80Case 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
81Case Study Inheriting Interface and
Implementation
- Create an array of Shape references
- Point to various subclass objects
- Call methods using Shape reference
82- 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
83- 1.4 Overridden method getName (required)
- ---------------------
- 1. Class Circle (extends Point)
- 1.1 protected data member
- 1.2 Constructors
- 1.3 New methods
84- 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
85- 1.2 Constructors
- 1.3 New methods
- 1.4 Overridden method area
- 1.5 Overridden method toString
- 1.6 Overridden method getName
86- 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
87- 2.1 Call methods using Shape references
88 89Case 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
90Case 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
91Case 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
92- 1. Shape interface
- 1.1 abstract methods
- -----------------------
- 1. Class Point(implements Shape)
93- 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
94- Use same class Test as before
95- Use same class Test as before
96 97Interface Hierarchies
- Inheritance can be applied to interfaces as well
as classes - One interface can be used as the parent of
another - The child interface inherits all abstract methods
of the parent - A class implementing the child interface must
define all methods from both the parent and child
interfaces - Note that class hierarchies and interface
hierarchies are distinct (they do not overlap)