Java Reference
In-Depth Information
method that returns a string as follows: “Pre-school” if the target age is 4
through 6, “Early” if the target age is 7 through 9, “Middle” if the target
age is 10 through 12, and “Upper” if the target age is 13 through 16.
SR 9.7
What is the difference between single inheritance and multiple
inheritance?
9.2 Overriding Methods
When a child class defines a method with the same name and signa-
ture as a method in the parent class, we say that the child's version
overrides the parent's version in favor of its own. The need for over-
riding occurs often in inheritance situations.
The program in Listing 9.7 provides a simple demonstration of
method overriding in Java. The Messages class contains a main
method that instantiates two objects: one from class Thought and
one from class Advice . The Thought class is the parent of the Advice class.
KEY CONCEPT
A child class can override (redefine)
the parent's definition of an inherited
method.
LISTING 9.7
//********************************************************************
// 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();
Advice dates = new Advice();
parked.message();
dates.message(); // overridden
}
}
 
Search WWH ::




Custom Search