Uploaded by Saketh Budideti

2017Ch11InheritanceLecture

advertisement
CHAPTER 11
INHERITANCE
Inheritance deals with relationships
and building new things using old things.
Inheritance
 Another
fundamental objectoriented technique is
inheritance, used to organize
and create reusable classes
 Software
reuse is at the heart
of inheritance
Inheritance


To derive a new class from an
existing one.
The programmer can add new
variables or methods, or can modify
the inherited methods.
Inheritance
The existing class is called the
…
 parent

class
superclass
 base
class
Inheritance
The derived class is called the …

child class

subclass.
As the name implies, the child inherits
characteristics (fields), and behaviors (methods)
of the parent class.
Inheritance
Superclass
(Base class)
Subclass extends
Superclass
Subclass
(Derived class)

Inheritance represents the IS-A
relationship between objects: an
object of a subclass IS-A(n) object of
the superclass.
Inheritance

Inheritance relationships often are shown
graphically in a UML class diagram, with an
arrow with an open arrowhead pointing to
the parent class
Vehicle
IS A
Car
Inheritance should create an is-a relationship, meaning
the child is a more specific version of the parent
An Inheritance Diagram
Parent of BankAccount
IS A
Parent of SavingsAccount
Child of Object
IS A
Child of BankAccount
A Mammal is an Animal.
A Dog is a Mammal.
Old Yeller is a Dog.
A Bird is an Animal.
A Chicken is a Bird.
Foghorn Leghorn is a Chicken.
X
is a
Y means X is an extension of Y
Syntax of Subclasses

In Java, we use the reserved word
extends to establish an inheritance
relationship
class subClassName extends superClassName
{
// class contents
}
public class B extends A
Inheritance essentially copies all of the methods
and instance variables from class A and pastes
those into class B at run time. The code from A is
run from within class B.
Inheritance and
constructors
Inheritance and
constructors


A subclass inherits all the fields and
methods of its superclass, but not
constructors.
We must call the parent constructor
like we would a method call in the
constructor of the child class.
The super Reference
 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
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 public or protected
variables and methods defined in the
parent’s class
Calling Superclass’s
Constructors (cont’d)

Superclass’s constructor calls its
superclass’s constructor, and so on, all
the way up to Object’s constructor.
Object
super( )
Biped
super(...)
Walker
Calling
Superclass’s
Constructors
Biped
Walker
public class Walker extends Biped
{
private int xval;
private int yval;
// Constructor
public Walker(int x, int y, char c, String n)
{
super(c, n);
Calls Biped’s
xval = x;
constructor
yval = y;
}
The number / types of parameters passed to
}
super must match parameters of one of the
superclass’s constructors.
If present, must be
the first statement
Inheriting instance fields
A
child will inherit all of it’s
parents instance fields,
HOWEVER, since they are
private, the only way to get at
them is via methods.
Inheritance and Fields
Inherit
field: All fields from the
superclass are automatically
inherited
Add
field: Supply a new field that
doesn't exist in the superclass
Can't
override fields
Access Specifiers



private members in the super class are
not accessible in the subclass.
protected members in the super class
– Are accessible in the subclass.
– Are not accessible outside the
package.
public members of a class are accessible
from anywhere (that you are using an
object)
The protected Modifier



The protected modifier allows a member
of a base class to be inherited into a child
Protected visibility provides more
encapsulation than public visibility does
However, protected visibility is not as
tightly encapsulated as private visibility
Recommended Access
Levels
• Fields: Always private
• Methods: public or private
• Classes: public
• Don't use protected on the
AP EXAM if you can help it.
//************************************************
// Words.java
Author: Lewis/Loftus
// Demonstrates the use of an inherited method.
//************************************************
public class Words
{
public static void main (String[] args)
{
Dictionary webster = new Dictionary ();
webster.pageMessage();
webster.definitionMessage();
}
}
//********************************************************
************
// 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; // note the use of protected, any child
// had access to this now.
public void pageMessage ()
{
System.out.println ("Number of pages: " + pages);
}
}
//********************************************************
// Dictionary.java
Author: Lewis/Loftus
// Represents a dictionary, which is a book. Used to demonstrate
// inheritance.
//********************************************************
public class Dictionary extends Book
{
private int definitions = 52500;
public void definitionMessage ()
{
System.out.println ("Number of definitions: " + definitions);
}
}
System.out.println ("Definitions per page: " + definitions/pages);
//**********************************************
// Words2.java
Author: Lewis/Loftus
// Demonstrates the use of the super reference.
//**********************************************
public class Words2
{
public static void main (String[] args)
{
Dictionary2 webster = new Dictionary2 (1500, 52500);
}
}
webster.pageMessage();
webster.definitionMessage();






















//********************************************************************
// Book2.java
Author: Lewis/Loftus
//
// Represents a book. Used as the parent of a dervied class to
// demonstrate inheritance and the use of the super reference.
//********************************************************************
public class Book2
{
private int pages;
// changed to private now
public Book2 (int numPages)
{
pages = numPages;
}
public int getPages ()
// added in
{
return pages;
}
public void pageMessage ()
{
System.out.println ("Number of pages: " + pages);
}
}
//*******************************************************************
*
// Dictionary2.java
Author: Lewis/Loftus
// Represents a dictionary, which is a book. Used to demonstrate
// the use of the super reference and a super method call
//*******************************************************************
*
public class Dictionary2 extends Book2
{
private int definitions;
public Dictionary2 (int numPages, int numDefinitions)
{
super (numPages);
}
definitions = numDefinitions;
public void definitionMessage ()
{
System.out.println ("Number of definitions: " + definitions);
}
}
System.out.println ("Definitions per page: " + definitions/super.getPages());
Inheritance and Methods
Inherit
method: Don't supply a new
implementation of a method that exists in
the superclass
Override method: Supply a different
implementation of a method that exists in
the superclass
Add method: Supply a new method that
doesn't exist in the superclass
Inheriting Methods
Since methods are public we inherit
all of them to the child class and
can use them WITHOUT rewriting
them!
Simply call them by their name.
super – refers to the parent class
super.parentMethod ( );
parentMethod();
Overriding Methods



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 has a different body
Since they both have the same name which
does it choose? The type of the object
executing the method determines which
version of the method is invoked
public class Monster
{
private String myName;
public Monster( String name ) {
myName = name;
}
public void overRide( ) {
System.out.println("overRide in Monster");
}
}
public class Witch extends Monster
{
public Witch( String name ) {
super(name);
}
public void overRide( ) {
System.out.println("overRide in Witch");
}
}
Overloading vs.
Overriding



Don't confuse the concepts of overloading
and 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
Add a method to the child
class
This
method is
available only in the
child class.
//*******************************************************
// Messages.java
Author: Lewis/Loftus
//
// Demonstrates the use of an overridden method.
//*******************************************************
public 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
public 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();
public 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()
{
System.out.println ("Warning: Dates in calendar are closer " +
"than they appear.");
System.out.println();
}
}
super.message();
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


Java does not support multiple inheritance
In most cases, the use of interfaces gives us aspects
of multiple inheritance without the overhead – this is
the next unit.
Class Hierarchies

A child class of one parent can be the
parent of another child, forming a
class hierarchy
Business
RetailBusiness
KMart
Macys
ServiceBusiness
Kinkos
Class Hierarchies

Two children of the same parent are called
siblings



Common features should be put as high in the
hierarchy as is reasonable
An inherited member is passed continually down
the line
Therefore, a child class inherits from all its
ancestor classes
Class Hierarchies (cont’d)

Help reduce
duplication of
code by factoring
out common code
from similar
classes into aWalker
Constructor
common
firstStep
superclass. nextStep
stop
distanceTraveled
Biped
Constructor
Accessors
turnLeft
turnRight
turnAround
draw
Hopper
Constructor
firstStep
nextStep
stop
distanceTraveled
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
Therefore, the Object class is the ultimate
root of all class hierarchies
Class Object is the one true super class.
Object does not extend any other class.
All classes extend Object.
Object
String
Date
© A+ Computer Science -
Because all classes are sub classes of
Object, all Java classes start with at least
the methods from Object.
String toString()
boolean equals(Object otherObject)
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 an existing definition
The toString method in the Object class is
defined to return a string that contains the name
of the object’s class together along with some
other information
Overriding the toString
Method
•
•
•
•
Returns a string representation of the object
Useful for debugging
toString used by concatenation operator
Object.toString prints class name and object
address
BankAccount@d2460bf
Example
public String toString( )
{
return name + age;
}
The Object Class




The equals method of the Object class returns
true if two references are aliases
We can override equals in any class to define
equality in some more appropriate way
The String class (as we've seen) defines the
equals method to return true if two String
objects contain the same characters
Therefore the String class has overridden the
equals method inherited from Object in favor
of its own version
Overriding the equals
Method
• equals tests for equal contents
• == tests for equal location
• Must cast the Object parameter to subclass
• public class Coin
{
public boolean equals(Object otherObject)
{
Coin other = otherObject;
return name.equals(other.name) && value ==
other.value;
}
}
//********************************************************************
// Academia.java
Author: Lewis/Loftus
//
// Demonstrates the use of methods inherited from the Object class.
//********************************************************************
public class Academia
{
public static void main (String[] args)
{
Student susan = new Student ("Susan", 5);
GradStudent frank = new GradStudent ("Frank", 3, "GTA", 12.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.");
public class Student
{
protected String name;
protected int numCourses;
public Student (String studentName, int courses)
{
name = studentName;
numCourses = courses;
}
public String toString()
{
String result = "Student name: " + name + "\n";
result += "Number of courses: " + numCourses;
}
return result;
public class GradStudent extends Student
{
private String source;
private double rate;
public GradStudent (String studentName, int courses,
String support, double payRate)
{
super (studentName, courses);
source = support;
rate = payRate;
}
public String toString()
{
String result = super.toString();
result += "\nSupport source: " + source + "\n";
result += "Hourly pay rate: " + rate;
}
return result;
Class Hierarchies

Using inheritance, a programmer can
define a hierarchy of classes.
Biped
Walker
ToedInWalker
Hopper
CharlieChaplin
NEXT SLIDE REFERS TO THIS HIERARCHY
Dancer
Polymorphic - the quality or state of existing in or
assuming different forms.
Polymorphism - In object-oriented programming, the term
is used to describe a variable that may refer to objects whose
class is not known at compile time and which respond at
run time according to the actual class of the object to
which they refer.
Using Polymorphism


You can store a child reference into a
parent reference but NOT a parent
into a child.
Example
Biped b = new Walker(); //OK
Walker w = new Biped(); //NO!
Polymorphism (cont’d)
The actual parameter passed to this
method can be a Walker, a Hopper,
etc.  any subclass of Biped.
public void moveAcross (Biped creature, int distance)
{
creature.firstStep();
while (creature.distanceTraveled () < distance)
creature.nextStep();
creature.stop();
}
Correct methods will be called automatically for
any specific type of creature: Walker’s methods
for Walker, Hopper’s for Hopper, etc.
Polymorphism – assume parent and
child have the same method.



A mechanism of selecting the
appropriate method for a particular
object in a class hierarchy.
The correct method is chosen based
upon the ACTUAL OBJECT that was
created (what followed new)
regardless of the type of reference
was used
Determined at run time
Example - BankAccount
CheckingAccount cAcct =
new CheckingAccount ();
BankAccount myAcct;
myAcct = cAcct;
Is this ok???
Example - BankAccount
CheckingAccount cAcct;
cAcct = new BankAccount();
How about this???
Exercise
Consider the classes below:
Array Polymorphism example

Given the classes on the previous slide,
these are valid since they each have a
computerTax method it will know which
class to go into by the ACTUAL OBJECT
that was created (what follows new)
Taxable [] assets = new Taxable[5];
assets[0] = new Stock();
assets[1] = new RealEstate();..
for (int i = 0;i < assets.length; ++i)
double d = assets[i].computeTax();
Not polymorphic



Assume the child class has a method
that a parent does not
If you assign a child object into a
parent reference and you want to get
at that method you must DOWNCAST.
It first looks for the method in the
parent class.
Example:
getId() is only in
GradStud



Student s = new GradStud();
s.getId() will first look in the Student
class and will not find it
DOWNCAST to tell it where to look for
this method.
((GradStud)s).getId()
Using Polymorphism - CASTING
The type on the left side of the assignment operator is
in the file where it looks for the method. If it is not
in that file you must CAST it to the class that
contains that method.
Parent x = new Child()
x.getMethod() // getMethod must be in parent class
If getMethod is not in the parent class but rather in
the child class you must cast it so it knows where
to look for it.
((Child)x).getMethod();
Downcasting Example
Consider the classes below:
Exercise
Taxable [] assets = new Taxable[5];
assets[0] = new Stock();
assets[1] = new RealEstate();..
for (int i = 0;i < assets.length; i++)
{
if(assets[i] instanceof Stock)
double d = ((Stock)assets[i]).getStockPrice();
if(assets[i] instanceof RealEstate)
String s = ((RealEstate)assest[i]).location();
}
Why do we have to cast?

If we have an array of Vehicles in a
garage, the array will hold an array of
REFERENCES to Vehicles, not the
actual vehicles themselves so if you
have a Vehicle c = new Car() and we
want to access a method from that
Car class which doesn’t exist in Vehicle
we need to tell it where to find that
method. It first looks in Vehicle since
that is the reference type.
public class Monster
{
private String myName;
public Monster() {
myName = "Monster";
}
public Monster( String name ) {
myName = name;
}
public String toString() {
return "Monster name :: " + myName +
"\n";
}
}
public class Witch extends Monster
{
}
public class Ghost extends Monster
{
}
Witch x = new Monster();
System.out.println(x);
Is this ok?
Monster x = new Witch();
Monster y = new Ghost();
System.out.println(x);
System.out.println(y);
Is this okay or not okay?
If okay what does it do?
x
0x2B7
0x2B7
"Wicked Witch"
Monster x = new Witch("Wicked Witch");
Monster reference x refers to a Witch!
x
0xE93
0xE93
0x2B7
"Casper"
"Wicked Witch"
x = new Ghost("Casper");
Monster reference x now refers to a Ghost!
Information hiding is a big part of good
design. Information hiding is
demonstrated with inheritance in that
super class code is written, tested, and
then tucked away. Sub classes can be
written using the super class methods
with no real concern for the
implementation details in the super
class methods.
The implicit Parameter
this – refers to the object/class
you are working in
this.toString( ); calls the toString of this class
this.x = 1524;
this( ); calls a constructor of this class
super – refers to the parent class
super.toString( );
Calls parent class toString method
super( ); parent default constructor call
super("elmo", 6); parent constructor call
class Skeleton extends Monster
{
private double speed;
public Skeleton( ) {
super();
A super call is always made on the 1st line
speed=100; of any sub class constructor.
}
public Skeleton( String name, double speed ) {
super(name);
super – refers to the parent
this.speed=speed;
}
public String toString( ) {
return super.toString() + " " + speed;
}
}
Download