Chapter 8 Inheritance

Download Report

Transcript Chapter 8 Inheritance

Inheritance

Another fundamental object-oriented technique is called
inheritance, which enhances software design and promotes
reuse

We will focus on:
• deriving new classes
• creating class hierarchies
• the protected modifier
• polymorphism via inheritance
• inheritance used in graphical user interfaces
1
The Three Pillars of OOP

The Three Pillars of OOP

Encapsulation
Inheritance
Polymorphism



Every class in Java extends some other class. If you don't
explicitly specify the class that your new class extends, it will
automatically extend the class named Object.
2
Class Hierarchy

Java uses a class hierarchy to organize its classes.

Thus, all classes in Java exist in a class hierarchy where the
class named Object forms the root of the hierarchy.

Some classes extend Object directly, while other classes are
subclasses of Object further down the hierarchy.
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 the child class or subclass.
4
Inheritance

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

This means that you can write the code for one class
and have all its child classes have access to it.
5
ClassVehicle
Method 1
Method 2
Method 3
Class Car
Inherits all of
the above
methods
6
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

Proper inheritance creates an is-a relationship, meaning
the child is a more specific version of the parent
7
Inheritance

A subclass inherits state and behavior.

Recall that an object’s state is reflected in the form of
instance variables and its behavior in the form of methods.

The child inherits both from all of its ancestors.
8
Inheritance
ClassVehicle
Method 1
Method 2
Method 3
Class Car
Inherits all of the above
methods and can add
methods of its own
9
Inheritance

A programmer can tailor a child 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
10
Child Classes

We have a class SHAPE and SHAPE has a child class
RECTANGLE and a child class TRIANGLE.

The SHAPE class will contain methods that are
common to both child classes, e.g. and Area() method

Both child classes will have a method that calculates its
Area. But will over ride the parent method.


Only the formulas for each Area calculation will differ.
The method in the child class deals with the behavior
that is particular to the child class.
11
Class Shape
Area ()
Class Rectangle
Inherits Area()
Class Triangle
Inherits Area()
12
Inheritance

This leads to smaller and easier to understand systems.

Using inheritance, common descriptions can be reused,
promoting the concept of code reusability.

A child class can have a method with the same name as
the parent class only its method implements what it is
capable of doing.
13
Inheritance

Inheritance cuts redundancy as descendant classes only
implement the extra information that differentiates them
from the parent class

When changes are made on the common information, all
child classes automatically inherit it.

Thus the models that are created are easier to modify and
implement.
14
Sub or Child Classes

In Java, the reserved word extends is used to
establish an inheritance relationship

To declare a subclass you would write:
class subclass extends SuperClass { . . . }
or,
class Dictionary extends Book{…}

A Java class can have only one direct superclass.
15
Sub or Child Classes
class Super
{
protected int num; // instance variable
public Super(int num) // constructor
{
this. num = num;
}
class Sub extends Super
{
private float num1; // instance variable
public Sub(int newnum, float num1)
{
super(newnum); // calls parent class constructor
this.num1 = num1;
}
16
Deriving Subclasses

In Java, we use the reserved word extends to establish an
inheritance relationship
class Car extends Vehicle
{
// class contents
}
17
Controlling 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
18
The protected Modifier

The protected visibility modifier allows a member of a
base class to be inherited into the child

The protected visibility modifier provides more
encapsulation than public does.

Encapsulation requires that we protect as much as possible
out instance variables from outside accesss.

The details of each modifier are given in Appendix F
19
Class Book
//------------------------------------------------------------------// Class Book serves as a parent class for class Dictionary
//------------------------------------------------------------------class Book
{
protected int pages = 1500;
//========================================
// Prints a message using the value of an instance variable.
//========================================
public void page_message ()
{
System.out.println ("Number of pages: " + pages);
} // method page_message
} // class Book
20
//------------------------------------------------------------------class Dictionary extends Book
{
private int definitions = 52500;
//=========================================
// Prints an instance variable declared in this class and
// an instance variable one that it inherited from Book
//======================================
public void definition_message ()
{
System.out.println ("# of definitions: " + definitions);
System.out.println ("Definitions per page: " +
definitions/pages);
} // method definition_message
} // class Dictionary
21
Class Words
class Words
{
//=====================================
// Instantiates a child class and invokes its inherited methods.
//=====================================
public static void main (String[] args)
{
Dictionary webster = new Dictionary ();
webster.page_message();
webster.definition_message();
} // method main
} // class Words
22
The super Reference

Constructors are not inherited, even though they have
public visibility

Yet we often need to call parent's constructor to set up the
"parent's part" of the object

The super reference is used to refer to the parent class,
and is used to invoke the parent's constructor

See Words2.java (page 328)
See Book2.java (page 329)
See Dictionary2.java (page 330)


23
//---------------------------------------------------------// Class Book ‘s constructor initializes pages
//-----------------------------------------------------------class Book
{
protected int pages; // instance variable
//=======================================
// Sets up a book with the specified number of pages.
//======================================
public Book (int num_pages)
{
pages = num_pages; // sets number of pages
} // constructor Book
//=======================================//
//prints out the number of pages in a book
//=======================================
public void page_message ()
{
System.out.println ("Number of pages: " + pages);
} // method page_message
} // class Book
24
//=======================================
// Class Dictionary demonstrates the interaction between the constructors of
parent and child classes.
//=======================================
class Dictionary extends Book
{
private int definitions;
//======================================
// Uses the super reference to call Book's constructor.
//=========================================
public Dictionary (int num_pages, int num_definitions)
{
// sets the # of pages in parent class
super (num_pages);
definitions = num_definitions; // sets # of definitions
} // constructor Dictionary
25
//---------------------------------------------------------// Driver class that creates an object of the Dictionary
// class.
//------------------------------------------------------------
class Words2
{
public static void main (String[] args)
{
Dictionary webster = new Dictionary (1500, 52500);
//webster calls method from the Book class
webster.page_message();
// webster calls method from Dictionary class
webster.definition_message();
} // method main
} // class Words2
26
Class Diagram for Words
Book
# pages : int
+ pageMessage() : void
Words
Dictionary
- definitions : int
+ main (args : String[]) : void
+ definitionMessage() : void
27
The Super Reference - Rules

In Words2.java, The Dictionary class uses the super reference to call
the parent constructor so that the number of pages can be set.

Java requires that a child class must call the parent class constructor
using super if the parent class constructor has a parameter.

This is to insure that the parent class’s instance variables are given
values.

If the parent class constructor has no parameters, the child class is not
required to call it. A default constructor is called for the parent class
instead.
28
Super Reference

When we create the constructor for a child class, we should
invoke the constructor for the superclass also.

To do this, the first line of our constructor should contain
the keyword super followed by a parameter list.

The parameter list must match the parameters in the
argument list of the superclass constructor.e.g.

super(num_pages) // initializes the # of pages
29
Super Reference

This causes the constructor for the superclass to be invoked
using parameters passed from the subclass.

The Dictionary class invokes the parent class constructor with:
super(num_pages)

Since the Dictionary class inherits the variable pages from the
parent class Book, it has to initialize this variable in its
constructor.
30
Inheritance and Constructors

Every constructor has 3 tasks to perform:
1. Instantiate the parent object and initialize its
fields
2. Initialize any fields local to its class
3. perform the statements in the constructor
31
Overloaded Constructors
 Another constructor that could be defined by Rectangle:
public Rectangle(int Newlength, int Newwidth)
{
length = Newlength;
width = Newwidth
}
 Both constructors share the same name, Rectangle, but they
have different parameter lists.
 The compiler determines which constructors to use based on
the number and types of the parameters/
32
32
Overloading Methods
 Method overloading is the process of using the same method
name for multiple methods. The signature of each overloaded
method must be unique
 The signature is based on the number, type, and order of
the parameters.
 The compiler must be able to determine which version of the
method is being invoked by analyzing the parameters. Thus,
one method must differ from another by the number and type
of parameters it uses.
 The return type of the method is not part of the signature
33
33
Overloading Methods
Version 1
Version 2
int tryMe (int x)
{
return x*x;
}
int tryMe (int x, float y)
{
return x*y;
}
Invocation
result = tryMe (25, 4.32)
34
34
Overloaded Methods
 The println method is overloaded:
println (String s)
println (int i)
println (double d)
etc.
 The following lines invoke different versions of
the println method:
System.out.println ("The total is:");
System.out.println (total);
35
35
Overriding Methods

A child class can override the definition of an inherited
method in favor of its own.

This is different from the overloading that we used in
constructors.

That is, a child can redefine a method 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
36
Overriding Methods




See Messages.java
See Thought.java
See Advice.java
Note that a parent method can be explicitly invoked using
the super reference
37
//**********************************************
// Contains a method that is overridden in a child class.
//**********************************************
class Thought
{
public void message()
{
System.out.println ("I feel like I'm diagonally parked " +
"in a parallel universe.");
} // method message
} // class Thought
38
//**********************************************
// Class Advice overrides the message method.
//**********************************************
class Advice extends Thought
{
// This method overrides the parent version
public void message()
{
System.out.println ("Warning: Dates in calendar are " +
"closer than they appear.");
} // method message
} // class Advice
39
///**********************************************
// Driver class that creates objects of parent and child //classes.
//**********************************************
class Messages
{
public static void main (String[] args)
{
Thought parked = new Thought(); // create Thought object
Advice dates = new Advice();// create Advice object
parked.message(); // calls method in Thought class
dates.message(); // calls method in Advice class
} // method main
} // class Messages
40
Overloading 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
41
Overriding Methods

To overload a method, you must duplicate the method
name, but use a different argument list.

To override a method, you must match the entire
method signature.
42
Overriding

If a method is declared with the final modifier, it cannot
be overridden

The concept of overriding can be applied to data and is
called shadowing variables. This occurs when you use the
same variable names in both the child and parent classes

Shadowing variables should be avoided because it tends to
cause unnecessarily confusing code
43
Class 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.

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
44
Single 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
45
The 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
46
The 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 object’s class
and a hash value
47
Class Object

The class Object defines the following methods:
•
•
•
•
•
•
•
•
•
•
•

clone()
equals(Object obj)
finalize()
getClass()
hashCode()
notify()
notifyAll()
toString()
wait()
wait(long timeout)
wait(long timeout, int nanos)
As you can see, this list includes three overloaded versions
of the method named wait (same name, different formal
argument lists).
48
Class Object

Because every class is either a direct or indirect subclass of
Object, every class in Java, (including new classes that you
define), inherit these eleven methods.

Generally speaking, many of these eleven methods are
intended to be overridden for various purposes.

However, some of them, such as getClass, notify, and wait,
are intended to be used directly without overriding.
49
The super Reference Revisited

A method in the parent class can be invoked explicitly using
the super reference

This ability is often helpful when using overridden methods
The syntax is:
super.method(parameters)



For instance, in the next example, the toString method in a
child class calls the toString method in the parent class with:
super.toString();
50
public class Student
{
protected String Firstname, Lastname;
protected int numCourses;
//----------------------------------------------------------------// Sets up a student with a name and number of courses.
//----------------------------------------------------------------public Student (String Firstname, String Lastname, int numCourses)
{
this.Firstname = Firstname;
this. Lastname = LastName
this.numCourses = numCourses;
}
//----------------------------------------------------------------// Returns information about this student as a string.
//----------------------------------------------------------------public String toString ()
{
String result = "Student name: " + Firstname + “ “ + Lastname "\n";
result += "Number of courses: " + numCourses;
return result;
}
51
//method to compare two objects
public boolean equals(Object other)
{
boolean result;
if (LastName.equals(((Student)other).LastName))
result = FirstName.equals(((Student)other).FirstName);
else
result = LastName.equals(((Student)other).LastName);
return result;
}
}
52
public class GradStudent extends Student
{
private String source;
private double rate;
//---------------------------------------------------------// Sets up the gradate student using the specified
// information.
//------------------------------------------------------------public GradStudent (String Fastname, String LastName ,int numCourses, String
source, double rate) {
super (Firstname, Lastname, numCourses);
this.source = source;
this.rate = rate;
}
//----------------------------------------------------------------// Returns a description of this graduate student as a string. – uses super to call
parent class toString()
//----------------------------------------------------------------public String toString (){
String result = super.toString();
result += "\nSupport source: " + source + "\n“ + "Hourly pay rate: " + rate;
return result;
}}
53
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", “James”, 4);
GradStudent Paul = new GradStudent ("Paul",”McCartney” , 1);
System.out.println (susan);
System.out.println ();
System.out.println (Paul);
System.out.println ();
if (! susan.equals(Paul))
System.out.println ("These are two different students.");
}
}
54
References 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 Christmas, then a Holiday reference could
actually be used to point to a Christmas object
I can do:
Holiday day = new Holiday();
Christmas day = new Christmas();



Holiday
OR:
Holiday day;
day = new Christmas();
Christmas
55
References and Inheritance

Assigning a child object to an ancestor reference is
considered to be a widening conversion, and can be
performed by simple assignment

Assigning an ancestor(parent) object to 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
56
Widening VS Narrowing Conversion

The only direct legal way to do a conversion is a widening
conversion.

A child object may be stored in an parent object as this is
a widening conversion

A parent object may not be stored in a child as it is a
narrowing conversion;

Legal
Error

parent = child
child = parent
57
Conversion

Legal
student = gradstudent(child)

Error

It is possible to store a child in a parent under certain
circumstances which we will address in the homework.
gradstudent = student(parent)
58
Polymorphism

What is polymorphism?

The meaning of the word polymorphism is something like
one name, many forms.

How does Java implement polymorphism?

Polymorphism manifests itself in Java in the form of
multiple methods having the same name.
59
Polymorphism


In some cases, multiple methods have the same name, but
different formal argument lists (overloaded methods).
•
In other cases, multiple methods have the same name, same
return type, and same formal argument list (overridden
methods).
Three distinct forms of polymorphism
 Method overloading
 Method overriding through inheritance
 Method overriding through the Java interface
60
Polymorphism via Inheritance

A polymorphic reference is one which can refer to different
types of objects at different times.

Inheritance can also 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
61
Class Account
# balance: double
+ deposit() : double
+ withdraw() : double
Class Senior Savings
+ deposit() : double
Over rides parent version
Inherits other parent methods and variables
62

We have an Accounts class which contains a deposit and withdraw
method. The SeniorSavings class extends it.

We create an array of Accounts objects.
Accounts[] customer= new Accounts[10];

We create an object of the Senior_Savings class
Senior_Savings Sam = new Senior_Savings(“Sam”);

We store Sam in the array
customer[5] = Sam;

We create an Accounts object called Ricky and store it in the array
Accounts Ricky = new Accounts(“Ricky”);
customer[3] = Ricky;

So the array customer of class Accounts holds both Senior-Savings and
regular Accounts because the two classes are related by inheritance
63
Polymorphism

The Senior_Savings class extends the Account class and
overrides the Account class method deposit with a
deposit method of its own.

The deposit method that is called depends on what type
of object is in the array.

If the object is a SeniorSavings object, its deposit
method will be called. If it is an Account object, the
parent version is called.
64
public class Bank
{
public static void main(String args[])
{
Account [] customer = new Account[10];
for (int i=0; i< 3; i++)
{
System.out.print ("Name of customer:);
String name = scan.next();
System.out.print ("Type of Account: S for Senior, R for regular ");
String type = scan.next();
if(type.charAt(0) == 'S')
customer[i] = new Senior_Savings(Name, acctype,accountnumber);
else if (acctype == 'R’)
customer[i] = new Account(Name, acctype, accountnumber);
} // close for
65

When we call the deposit method in a loop , the deposit
method that is is called depends on whether the object in
the array is of the Account class or the SeniorSavings class.
if(acctype == 'S')
{
customer[i] = new SeniorSavings(name, acctype,
accnum++);
customer[i].deposit(45); // SeniorSavings version called
}
else if (acctype == 'R’)
{
customer [i] = new Account(name, acctype, acctnum++);
customer[i].deposit(75); // Account version called
}
66
Another Polymorphism Example
Let’s look at another example of polymorphism.
Recall the classes we did earlier, classes Advice
and Thought. Class Advice extends class
Thought and overrides the message method;
67
Class Thought
// Class Thought has one method
/***************************************************
class Thought
{
public void message()
{
System.out.println ("Some people get lost in thought " +
"because it's unfamiliar territory.");
} // method message
} // class Thought
68
Class Advice extends Thought
/***************************************************
// class Advice is a child class of Thought and over rides the
parent version of Advice
/***************************************************
class Advice extends Thought
{
public void message()
{
System.out.println ("Avoid cliches like the plague.");
} // method message
} // class Advice
69
class Messages2
{
public static void main (String[] args)
{
Thought Territory = new Thought();
Advice Cliche = new Advice();
// call the message method in each class
Territory.message();
Cliche.message();
// Territory & Cliché now point to same address
Territory = Cliche;
// the message method from the Advice class is printed
Territory.message();
} // method main
} // class Messages
70
Polymorphism

In general, it is the type of the object being referenced
determines which method is invoked.


Objects of Thought class and Advice class are
instantiated. They both contain a method called message.

Initially, they each call their respective methods. Then the
Thought object is assigned the value of theAdvice object.
71
Polymorphism

When the message method is invoked by the Thought object,
the advice version is executed.

Note that, if an invocation is in a loop, the exact same line of
code could execute different methods at different times.

Before the JDK 1.5, all polymorphic references were resolved
at run-time because it may not be known what the type is until
then.

However, with the new JDK1.5, there is a way to do it at
compile time which we will discuss later.
72
Final Methods
A final method cannot be overridden.
Declaring a method final prevents the derived class from
erroneously redefining a class method.
Declaring a method final allows the compiler to perform
inline optimization.
final classes cannot be extended.
73
Class Hierarchies

A child class of one parent can be the parent of another
child, forming class hierarchies
Business
RetailBusiness
KMart
Macys
ServiceBusiness
Penny’s
74