Transcript Chapter08.1
Chapter 8
Inheritance
Part 1
Inheritance
• Inheritance is a fundamental object-oriented
design technique used to create and organize
reusable classes
• Chapter 8 focuses on:
deriving new classes from existing classes
the protected modifier
creating class hierarchies
abstract classes
indirect visibility of inherited members
designing for inheritance
the GUI component class hierarchy
extending listener adapter classes
the Timer class
© 2004 Pearson Addison-Wesley. All rights reserved
8-2
Outline
Creating Subclasses
Overriding Methods
Class Hierarchies
Inheritance and Visibility
Designing for Inheritance
Inheritance and GUIs
The Timer Class
© 2004 Pearson Addison-Wesley. All rights reserved
8-3
Inheritance
• 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 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 by the parent class
© 2004 Pearson Addison-Wesley. All rights reserved
8-4
Inheritance
• Inheritance relationships are shown in a UML class
diagram using a solid arrow with an unfilled
triangular arrowhead pointing to the parent class
Vehicle
Car
Please note: a ‘dashed’
arrow with same triangle
means ‘realizes’ in UML.
This is quite different! There
are not many of these
symbols, but you definitely
need to learn the ones we see.
• Proper inheritance creates an is-a relationship,
meaning the child is a more specific version of the
parent
© 2004 Pearson Addison-Wesley. All rights reserved
8-5
Inheritance
• A programmer can tailor a derived class as needed
by adding new variables or methods, or by
modifying the inherited ones
• Software reuse is a fundamental benefit of
inheritance
• By using existing software components to create
new ones, we capitalize on all the effort that went
into the design, implementation, and testing of the
existing software
• Component-based software development is HUGE
in the industry today!
© 2004 Pearson Addison-Wesley. All rights reserved
8-6
Deriving Subclasses
• In Java, we use the reserved word extends to
establish an inheritance relationship
derived class
(child class)
class Car extends Vehicle
{
// class contents
}
base class
(parent class)
• Let’s look at some code…
© 2004 Pearson Addison-Wesley. All rights reserved
8-7
//********************************************************************
// Words.java
Author: Lewis/Loftus
//
// Demonstrates the use of an inherited method.
//********************************************************************
public class Words
{
//----------------------------------------------------------------// Instantiates a derived class and invokes its inherited and local methods.
//----------------------------------------------------------------public static void main (String[] args)
{
Dictionary webster = new Dictionary();
System.out.println ("Number of pages: " + webster.getPages());
System.out.println ("Number of definitions: " + webster.getDefinitions());
System.out.println ("Definitions per page: " + webster.computeRatio());
} // end main()
} // end Words
Looks simple enough. Creating an object webster of type Dictionary.
Then we are executing a few of webster’s methods (from the class…)
So, we need to see what the Dictionary class looks like, right?
© 2004 Pearson Addison-Wesley. All rights reserved
8-8
//********************************************************************
// Dictionary.java
Author: Lewis/Loftus
// Represents a dictionary, which is a book. Used to demonstrate
// inheritance.
//********************************************************************
public class Dictionary extends Book But we note that Dictionary ‘inherits’ Book!
{
// Parent (super, or base) class is Book. Dictionary is a derived
// class, and our object, webster, is an object of the derived class
// Dictionary.
private int definitions = 52500;
//----------------------------------------------------------------// Prints a message using both local and inherited values.
//----------------------------------------------------------------public double computeRatio ()
{
return definitions/pages;
Note methods here in
} // end computeRation()
// Definitions mutator. ========================
public void setDefinitions (int numDefinitions)
{
definitions = numDefinitions;
} // end mutator
// Definitions accessor. =========================
public int getDefinitions ()
{
return definitions;
} // end accessor
} // end Dictionary
© 2004 Pearson Addison-Wesley. All rights reserved
Dictionary (usable by
webster, of course.
Again, mutator and
accessor methods are
quite common.
Now, onto the base class!
8-9
//********************************************************************
// Book.java
Author: Lewis/Loftus
//
// Represents a book. Used as the parent of a derived class to demonstrate
inheritance.
//********************************************************************
public class Book
{
protected int pages = 1500;
// instance variable for objects.
// Pages mutator.
public void setPages (int numPages)
{
pages = numPages;
} // end setPages
// Pages accessor.
public int getPages ()
{
return pages;
} // end getPages()
} // end Book
© 2004 Pearson Addison-Wesley. All rights reserved
Standard mutator and
accessor (get and set
methods…)
Let’s go back to the main one…
8-10
//********************************************************************
// Words.java
Author: Lewis/Loftus
//
// Demonstrates the use of an inherited method.
//********************************************************************
public class Words
{
//----------------------------------------------------------------// Instantiates a derived class and invokes its inherited and local methods.
Where from?
//----------------------------------------------------------------NOT in
public static void main (String[] args)
Dictionary!!
{
Dictionary webster = new Dictionary();
System.out.println ("Number of pages: " + webster.getPages());
System.out.println ("Number of definitions: " + webster.getDefinitions());
System.out.println ("Definitions per page: " + webster.computeRatio());
} // end main()
} // end Words
We KNOW where these
are from.
Looks simple enough. Creating an object webster of type Dictionary.
Then we are executing a few of webster’s methods (from the class…)
So, we need to see what the Dictionary class looks like, right?
© 2004 Pearson Addison-Wesley. All rights reserved
8-11
Book
Dictionary
Here is our UML diagram showing inheritance.
Dictionary is a derived class from Book, the base class.
Webster is an object of type Dictionary.
Objects are not shown in a class diagram, as above.
Of course, all attributes and methods in Book are inherited by
Dictionary. Thus any object of type Dictionary has access to
all methods and attributes of all.
© 2004 Pearson Addison-Wesley. All rights reserved
8-12
The protected Modifier
• Visibility modifiers affect the way that class
members can be used in a child class
• Variables and methods declared with private
visibility cannot be referenced by name in a child
class
• They can be referenced in the child class if
they are declared with public visibility -- but
public variables violate the principle of
encapsulation!!!
• There is a third visibility modifier that helps in
inheritance situations: protected
© 2004 Pearson Addison-Wesley. All rights reserved
8-13
The protected Modifier
• The protected modifier allows a child class to
reference a variable or method directly in the child
class
• It provides more encapsulation than public
visibility, but is not as tightly encapsulated as
private visibility
• A protected variable is visible to any class in the
same package as the parent class
• The details of all Java modifiers are discussed in
Appendix E
• Protected variables and methods can be shown
with a # symbol preceding them in UML diagrams
© 2004 Pearson Addison-Wesley. All rights reserved
8-14
Final Class Diagram for Words
Book
“Inherits from” or
A Dictionary ‘is_a’ Book.
Words
# pages : int
+ pageMessage() : void
Dictionary
- definitions : int
+ main (args : String[]) : void
+ definitionMessage() : void
“uses” or “depends on” (means likely that it sends
messages and requires some services….)
(Objects of type Dictionary inherit pageMessage(),
and pages (attribute), etc. from base class.)
© 2004 Pearson Addison-Wesley. All rights reserved
8-15
The 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 often is used to invoke the
parent's constructor
• OK. So, let’s look further into inheritance to some
VERY important principles.
© 2004 Pearson Addison-Wesley. All rights reserved
8-16
// Words2.java
Author: Lewis/Loftus
// Demonstrates the use of the super reference.
public class Words2
{
// Instantiates a derived class and invokes its inherited and local methods.
Creating an object
public static void main (String[] args)
of type Dictionary2
{
Dictionary2 webster = new Dictionary2 (1500, 52500);
Constructor needs
two arguments.
System.out.println ("Number of pages: " + webster.getPages());
System.out.println ("Number of definitions: " +
webster.getDefinitions());
System.out.println ("Definitions per page: " +
webster.computeRatio());
} // end main()
} // end Words2
© 2004 Pearson Addison-Wesley. All rights reserved
So, let’s look to see
what Dictionary2
looks like….
8-17
// Dictionary2.java
Author: Lewis/Loftus
// Represents a dictionary, which is a book. Used to demonstrate the use of the super reference.
public class Dictionary2 extends Book2 We know this means inheritance from Book2.
{
private int definitions;
// Constructor: Sets up the dictionary with the specified number of pages and definitions.
public Dictionary2 (int numPages, int numDefinitions)
{
super(numPages); This means that the argument passed to the constructor is used to
initialize the attribute (variable) numPages in the base class! What is happening
is that this method call passes the argument numPages to the Constructor of
the base class to initialize ‘pages’ in the base class.
definitions = numDefinitions; This is used to initialize the instance variable, definitions.
} // end Constructor.
// Prints a message using both local and inherited values.
public double computeRatio ()
{
return definitions/pages; uses attributes of object (instance variable definitions)
divided by the attribute of the base class (pages) which was inherited.
} // end computeRatio()
// Definitions mutator.
public void setDefinitions (int numDefinitions)
{
definitions = numDefinitions; used to set instance variable.
} // end setDefinitions()
etc.
} // end Dictionary2
© 2004 Pearson Addison-Wesley. All rights reserved
8-18
// Book2.java
Author: Lewis/Loftus
// Represents a book. Used as the parent of a derived class to
// demonstrate inheritance and the use of the super reference.
//********************************************************************
public class Book2
{
protected int pages;
Note ‘protected’
//---------------------------------------------------------------// Constructor: Sets up the book with the specified number of pages.
//---------------------------------------------------------------public Book2 (int numPages)
{
pages = numPages;
} // end Constructor
// Pages mutator. ---------------------------------------public void setPages (int numPages)
{
pages = numPages;
} // end setPages()
// Pages accessor. --------------------------------------public int getPages ()
{
return pages;
} // end getPages()
2004 Pearson Addison-Wesley. All rights reserved
} end©Book2
Nothing special.
Constructor needs an int.
Protected means derived
class (and hence objects of
derived class) can access
the attribute: pages.
8-19
The super Reference
• A child’s constructor is responsible for calling the
parent’s constructor
• The first line of a child’s constructor should use
the super reference to call the parent’s
constructor
• The super reference can also be used to reference
other variables and methods defined in the
parent’s class
• This can be useful when there is a conflict… that
is, a derived class and the base class have the
same method name. Clearly derived class’s
method would be inherited by an object, unless
the
object needs the parent’s version.
© 2004 Pearson Addison-Wesley. All rights reserved
8-20
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
• Java does not support multiple inheritance
• In most cases, the use of interfaces gives us
aspects of multiple inheritance without the overhead
In actuality, the simulate multiple inheritance, you might use
a combination of regular inheritance plus an interface.
© 2004 Pearson Addison-Wesley. All rights reserved
8-21
Outline
Creating Subclasses
Overriding Methods
Class Hierarchies
Inheritance and Visibility
Designing for Inheritance
Inheritance and GUIs
The Timer Class
© 2004 Pearson Addison-Wesley. All rights reserved
8-22
Overriding Methods (not Overloading!)
• A child class can override the definition of an inherited
method in favor of its own
• The new method must have the same signature as the
parent's method, but can have a different body
• The type of the object executing the method
determines which version of the method is invoked
• This goes to polymorphism too. Very important!
Next chapter.
© 2004 Pearson Addison-Wesley. All rights reserved
8-23
//********************************************************************
// Messages.java
Author: Lewis/Loftus
// Demonstrates the use of an overridden method.
public class Messages
{
//----------------------------------------------------------------// Creates two objects and invokes the message method in each.
//----------------------------------------------------------------public static void main (String[] args)
{
Thought parked = new Thought(); creates object of type
Thought (a base class…)
Advice dates = new Advice(); creates object of type Advice,
a derived class of Thought.
parked.message(); Goes to Thought…Prints out simple message.
Method of base class invoked directly via inheritance.
dates.message(); // overridden Goes to Advice (object of class
derived from base class, Thought. Prints out message from Advice and
THEN prints out message from Thought invoked via the super method.
} // end main()
} // end Messages
© 2004 Pearson Addison-Wesley. All rights reserved
8-24
//********************************************************************
// Thought.java
Author: Lewis/Loftus
//
// Represents a stray thought. Used as the parent of a derived
// class to demonstrate the use of an overridden method.
//********************************************************************
public class Thought This turns out to be a base class.
{
//----------------------------------------------------------------// Prints a message.
//----------------------------------------------------------------public void message()
{
System.out.println ("I feel like I'm diagonally parked in a " +
"parallel universe.");
System.out.println();
} // end message()
} // end Thought
© 2004 Pearson Addison-Wesley. All rights reserved
8-25
//********************************************************************
/// Advice.java
Author: Lewis/Loftus
///
*// Represents some thoughtful advice. Used to demonstrate the use
*// of an overridden method.
*//********************************************************************
*
*public class Advice extends Thought
{
* //----------------------------------------------------------------* // Prints a message. This method overrides the parent's version.
* //----------------------------------------------------------------* public void message()
* {
* System.out.println ("Warning: Dates in calendar are closer " +
"than they appear.");
*
*
* System.out.println();
* super.message(); // explicitly invokes the parent's version
* } // end message()
*} // end Advice
*
© 2004 Pearson Addison-Wesley. All rights reserved
*
8-26
Overriding
• A method in the parent class can be invoked
explicitly 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
too and is called shadowing variables
• Shadowing variables should be avoided
because it tends to cause unnecessarily confusing
code
© 2004 Pearson Addison-Wesley. All rights reserved
8-27
Overloading vs. Overriding
• Overloading deals with multiple methods with
the same name in the same class, but with
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 parameters
• Overriding lets you define a similar operation in
different ways for different object types
© 2004 Pearson Addison-Wesley. All rights reserved
8-28