0% found this document useful (0 votes)
8 views131 pages

Understanding Inheritance in Java

The document discusses inheritance in Java, a key object-oriented design technique for creating reusable classes. It covers concepts such as creating subclasses, the protected modifier, class hierarchies, and the use of the super reference. Additionally, it highlights the benefits of inheritance for software reuse and encapsulation.

Uploaded by

bilgehancan550
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views131 pages

Understanding Inheritance in Java

The document discusses inheritance in Java, a key object-oriented design technique for creating reusable classes. It covers concepts such as creating subclasses, the protected modifier, class hierarchies, and the use of the super reference. Additionally, it highlights the benefits of inheritance for software reuse and encapsulation.

Uploaded by

bilgehancan550
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Week 5 & 6

Inheritance

Java Software Solutions


Foundations of Program Design
Seventh Edition

John Lewis
William Loftus

Copyright © 2012 Pearson Education, Inc.


Inheritance
• Inheritance is a fundamental object-oriented design
technique used to create and organize reusable classes
• Chapter 9 focuses on:
– deriving new classes from existing classes
– the protected modifier
– creating class hierarchies
– abstract classes
– indirect visibility of inherited members
– designing for inheritance

Copyright © 2012 Pearson Education, Inc.


Outline

Creating Subclasses
Overriding Methods
Class Hierarchies
Visibility
Designing for Inheritance

Copyright © 2012 Pearson Education, Inc.


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
• 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
Copyright © 2012 Pearson Education, Inc.
Inheritance
• A programmer can tailor a derived class as needed
by adding new variables or methods, or by
modifying the inherited ones

• One benefit of inheritance is software reuse

• 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

Copyright © 2012 Pearson Education, Inc.


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
Copyright © 2012 Pearson Education, Inc.
Superclasses and Subclasses (Cont.)
⬛ Not every class relationship is an
inheritance relationship.

⬛ Has-a relationship
▪ Create classes by composition of existing classes.
▪ Example: Given the classes Employee,
BirthDate and ContactInfo, it’s improper to say
that an Employee is a BirthDate or that an
Employee is a ContactInfo.
▪ However, an Employee has a BirthDate, and an
Employee has a ContactInfo.

© Copyright 1992-2012 by Pearson Education, Inc. All Rights


Reserved.
Superclasses and Subclasses

⬛ Superclasses tend to be “more general” and subclasses “more


specific.”

© Copyright 1992-2012 by Pearson Education, Inc. All Rights


Reserved.
Superclasses and Subclasses (Cont.)
⬛ Below is Shape inheritance hierarchy.
⬛ Follow the arrows from the bottom of the diagram to the

topmost superclass to identify several is-a relationships.


▪ A Triangle is a TwoDimensionalShape and is a Shape
▪ A Sphere is a ThreeDimensionalShape and is a Shape.

© Copyright 1992-2012 by Pearson Education, Inc. All Rights


Reserved.
• A sample university community class hierarchy
• Also called an inheritance hierarchy.
• Each arrow in the hierarchy represents an is-a relationship.
• Follow the arrows upward in the class hierarchy
• “an Employee is a CommunityMember”
• “a Teacher is a Faculty member.”

© Copyright 1992-2012 by Pearson Education, Inc. All Rights


Reserved.
Deriving Subclasses
• In Java, we use the reserved word extends to
establish an inheritance relationship

public class Car extends Vehicle


{
// class contents
}

• See [Link]
• See [Link]
• See [Link]

Copyright © 2012 Pearson Education, Inc.


//********************************************************************
// [Link] Author: Lewis/Loftus
//
// Represents a book. Used as the parent of a derived class to
// demonstrate inheritance.
//********************************************************************

public class Book


{
protected int pages = 1500;

//----------------------------------------------------------------
// Pages mutator.
//----------------------------------------------------------------
public void setPages (int numPages)
{
pages = numPages;
}

//----------------------------------------------------------------
// Pages accessor.
//----------------------------------------------------------------
public int getPages ()
{
return pages;
}
}

Copyright © 2012 Pearson Education, Inc.


//********************************************************************
// [Link] Author: Lewis/Loftus
//
// Represents a dictionary, which is a book. Used to demonstrate
// inheritance.
//********************************************************************

public class Dictionary extends Book


{
private int definitions = 52500;

//-----------------------------------------------------------------
// Prints a message using both local and inherited values.
//-----------------------------------------------------------------
public double computeRatio ()
{
return (double) definitions/pages;
}

continue

Copyright © 2012 Pearson Education, Inc.


continue

//----------------------------------------------------------------
// Definitions mutator.
//----------------------------------------------------------------
public void setDefinitions (int numDefinitions)
{
definitions = numDefinitions;
}

//----------------------------------------------------------------
// Definitions accessor.
//----------------------------------------------------------------
public int getDefinitions ()
{
return definitions;
}
}

Copyright © 2012 Pearson Education, Inc.


//********************************************************************
// [Link] 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();

[Link] ("Number of pages: " + [Link]());

[Link] ("Number of definitions: " +


[Link]());

[Link] ("Definitions per page: " +


[Link]());
}
}

Copyright © 2012 Pearson Education, Inc.


Output
//********************************************************************
// [Link] Author: Lewis/Loftus
// Number of pages: 1500
// Demonstrates theNumber
use ofof
andefinitions: 52500
inherited method.
//********************************************************************
Definitions per page: 35.0
public class Words
{
//-----------------------------------------------------------------
// Instantiates a derived class and invokes its inherited and
// local methods.
//-----------------------------------------------------------------
public static void main (String[] args)
{
Dictionary webster = new Dictionary();

[Link] ("Number of pages: " + [Link]());

[Link] ("Number of definitions: " +


[Link]());

[Link] ("Definitions per page: " +


[Link]());
}
}

Copyright © 2012 Pearson Education, Inc.


Class Diagram for Words

Book
# pages : int

+ pageMessage() : void

Words Dictionary
- definitions : int
+ main (args : String[]) : void
+ definitionMessage() : void

Copyright © 2012 Pearson Education, Inc.


Example: Modeling a Coffee Machine
VendingMachine
The class CoffeeMachine is
discovered first, then the class
SodaMachine, then the
superclass
VendingMachine

CoffeeMachine SodaMachine

totalReceipts totalReceipts
numberOfCups cansOfBeer
coffeeMix cansOfCola
collectMoney() collectMoney()
makeChange() makeChange()
heatWater() chill()
dispenseBeverage() dispenseBeverage()
addSugar()
addCreamer()
Example: Modeling a Coffee Machine
VendingMachine
VendingMachine
totalReceipts
collectMoney()
makeChange()
dispenseBeverage()

SodaMachine
CoffeeMachine
totalReceipts totalReceipts
cansOfBeer
numtotalReceiptsberOfCups
coffeeMix cansOfCola

collectMoney() collectMoney() CoffeeMachine


SodaMachine
makeChange() makeChange()
numberOfCups
heatWater() chill() cansOfBeer
coffeeMix
dispenseBeverage()dispenseBeverage() cansOfCola
addSugar() heatWater()
addCreamer() addSugar() chill()
addCreamer()
An Example of a Specialization
CandyMachine is a new
VendingMachine product and designed as a sub
class of the superclass
totalReceipts VendingMachine
collectMoney()
makeChange()
dispenseBeverage() A change of names might now
be useful: dispenseItem()
instead of
dispenseBeverage() and
dispenseSnack()

CoffeeMachine
SodaMachine CandyMachine
numberOfCups
coffeeMix cansOfBeer bagsofChips
cansOfCola numberOfCandyBars
heatWater()
addSugar() chill() dispenseSnack()
addCreamer()
Example of a Specialization (2)

Vending Machine
totalReceipts
collectMoney()
makeChange()
dispenseItem()

CoffeeMachine
SodaMachine
numberOfCups CandyMachine
coffeeMix cansOfBeer
cansOfCola bagsofChips
heatWater() numberOfCandyBars
addSugar() chill()
addCreamer() dispenseItem() dispenseItem()
dispenseItem()
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 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

Copyright © 2012 Pearson Education, Inc.


The protected Modifier
• The protected modifier allows a child class to
reference a variable or method in the child class

• It provides more encapsulation than public visibility,


but is not as tightly encapsulated as private visibility

• A protected variable is also visible to any class in


the same package as the parent class

• Protected variables and methods can be shown


with a # symbol preceding them in UML diagrams

Copyright © 2012 Pearson Education, Inc.


protected Members
⬛A class’s public members are accessible wherever
the program has a reference to an object of that class
or one of its subclasses.
⬛A class’s private members are accessible only
within the class itself.
⬛protected access is an intermediate level of access
between public and private.
▪ A superclass’s protected members can be accessed by
members of that superclass, by members of its subclasses and
by members of other classes in the same package
▪ protected members also have package access.

© Copyright 1992-2012 by Pearson Education, Inc. All Rights


Reserved.
protected Members (Cont.)
⬛ A superclass’s private members are hidden in its subclasses
▪ They can be accessed only through the public or protected methods
inherited from the superclass
⬛Subclass methods can refer to public and protected members
inherited from the superclass simply by using the member
names.
⬛the superclass method can be accessed from the subclass by

preceding the superclass method name with keyword super


and a dot (.) separator.

© Copyright 1992-2012 by Pearson Education, Inc. All Rights


Reserved.
Final Keyword
• Final can be:
– variable – method - class
If you make any variable as final, If you make any class as final, you cannot
you cannot change the value of final extend it.
variable(It will be constant).

Copyright © 2012 Pearson Education, Inc.


Private Keyword
• The private access modifier is If you make any class constructor private,
accessible only within the class. you cannot create the instance of that
class from outside the class.

Copyright © 2012 Pearson Education, Inc.


Protected Keyword
The protected keyword is an access modifier
used for attributes, methods and constructors,
making them accessible in the same package
and subclasses.

The protected access modifier can be


applied on the data member, method and
constructor. It can't be applied on the
class.

Copyright © 2012 Pearson Education, Inc.


Private Method vs. Final Method
- private is an access modifier, while final is a
modifier which puts additional constraints
- you cannot use private methods outside the class,
the final method can be used.
- you cannot override both private and final
methods.
- You cannot create an instance of a class with a
private constructor outside the class boundary,

Copyright © 2012 Pearson


Education, Inc.
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
• A child’s constructor is responsible for calling the
parent’s constructor

Copyright © 2012 Pearson Education, Inc.


The super Reference
• 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
• See [Link]
• See [Link]
• See [Link]

Copyright © 2012 Pearson Education, Inc.


//********************************************************************
// [Link] 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;

//----------------------------------------------------------------
// Constructor: Sets up the book with the specified number of
// pages.
//----------------------------------------------------------------
public Book2 (int numPages)
{
pages = numPages;
}

continue

Copyright © 2012 Pearson Education, Inc.


continue

//----------------------------------------------------------------
// Pages mutator.
//----------------------------------------------------------------
public void setPages (int numPages)
{
pages = numPages;
}

//----------------------------------------------------------------
// Pages accessor.
//----------------------------------------------------------------
public int getPages ()
{
return pages;
}
}

Copyright © 2012 Pearson Education, Inc.


//********************************************************************
// [Link] Author: Lewis/Loftus
//
// Represents a dictionary, which is a book. Used to demonstrate
// the use of the super reference.
//********************************************************************

public class Dictionary2 extends 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);

definitions = numDefinitions;
}

continue

Copyright © 2012 Pearson Education, Inc.


continue

//-----------------------------------------------------------------
// Prints a message using both local and inherited values.
//-----------------------------------------------------------------
public double computeRatio ()
{
return (double) definitions/pages;

// return (double) definitons/[Link]();


}

//----------------------------------------------------------------
// Definitions mutator.
//----------------------------------------------------------------
public void setDefinitions (int numDefinitions)
{
definitions = numDefinitions;
}

//----------------------------------------------------------------
// Definitions accessor.
//----------------------------------------------------------------
public int getDefinitions ()
{
return definitions;
}
}
Copyright © 2012 Pearson Education, Inc.
//********************************************************************
// [Link] Author: Lewis/Loftus
//
// Demonstrates the use of the super reference.
//********************************************************************

public 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);

[Link] ("Number of pages: " + [Link]());

[Link] ("Number of definitions: " +


[Link]());

[Link] ("Definitions per page: " +


[Link]());
}
}

Copyright © 2012 Pearson Education, Inc.


Output
//********************************************************************
// [Link] Author: Lewis/Loftus
// Number of pages: 1500
// Demonstrates theNumber
use of of
thedefinitions: 52500
super reference.
//********************************************************************
Definitions per page: 35.0
public 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);

[Link] ("Number of pages: " + [Link]());

[Link] ("Number of definitions: " +


[Link]());

[Link] ("Definitions per page: " +


[Link]());
}
}

Copyright © 2012 Pearson Education, Inc.


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
• Multiple inheritance is generally not needed, and
Java does not support it

Copyright © 2012 Pearson Education, Inc.


Outline

Creating Subclasses
Overriding Methods
Class Hierarchies
Visibility
Designing for Inheritance

Copyright © 2012 Pearson Education, Inc.


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 can have a different body

• The type of the object executing the method


determines which version of the method is invoked

• See [Link]
• See [Link]
• See [Link]
Copyright © 2012 Pearson Education, Inc.
//********************************************************************
// [Link] 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


{
//-----------------------------------------------------------------
// Prints a message.
//-----------------------------------------------------------------
public void message()
{
[Link] ("I feel like I'm diagonally parked in a " +
"parallel universe.");

[Link]();
}
}

Copyright © 2012 Pearson Education, Inc.


//********************************************************************
// [Link] 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()
{
[Link] ("Warning: Dates in calendar are closer " +
"than they appear.");

[Link]();

[Link](); // explicitly invokes the parent's version


}
}

Copyright © 2012 Pearson Education, Inc.


//********************************************************************
// [Link] 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();

[Link]();

[Link](); // overridden
}
}

Copyright © 2012 Pearson Education, Inc.


Output
//********************************************************************
// [Link] Author: Lewis/Loftus
// I feel like I'm diagonally parked in a parallel universe.
// Demonstrates the use of an overridden method.
Warning: Dates in calendar are closer than they appear.
//********************************************************************

public class
I feel Messages
like I'm diagonally parked in a parallel universe.
{
//-----------------------------------------------------------------
// Creates two objects and invokes the message method in each.
//-----------------------------------------------------------------
public static void main (String[] args)
{
Thought parked = new Thought();
Advice dates = new Advice();

[Link]();

[Link](); // overridden
}
}

Copyright © 2012 Pearson Education, Inc.


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
and is called shadowing variables
• Shadowing variables should be avoided because it
tends to cause unnecessarily confusing code

Copyright © 2012 Pearson Education, Inc.


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
Copyright © 2012 Pearson Education, Inc.
Quick Check
True or False?
A child class may define a method with
the same name as a method in the parent.
A child class can override the constructor
of the parent class.
A child class cannot override a final method
of the parent class.
It is considered poor design when a child
class overrides a method from the parent.
A child class may define a variable with the
same name as a variable in the parent.
Copyright © 2012 Pearson Education, Inc.
Quick Check
True or False?
A child class may define a method with True
the same name as a method in the parent.
A child class can override the constructor False
of the parent class.
A child class cannot override a final method True
of the parent class.
It is considered poor design when a child False
class overrides a method from the parent.
A child class may define a variable with the True, but
same name as a variable in the parent. shouldn't
Copyright © 2012 Pearson Education, Inc.
Outline

Creating Subclasses
Overriding Methods
Class Hierarchies
Visibility
Designing for Inheritance

Copyright © 2012 Pearson Education, Inc.


Class Hierarchies
• A child class of one parent can be the parent of
another child, forming a class hierarchy

Copyright © 2012 Pearson Education, Inc.


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
• There is no single class hierarchy that is
appropriate for all situations

Copyright © 2012 Pearson Education, Inc.


The Object Class
• A class called Object is defined in the [Link]
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

Copyright © 2012 Pearson Education, Inc.


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 define the toString method, we


are actually overriding an inherited definition

• The toString method in the Object class is


defined to return a string that contains the name of
the object’s class along with a hash code

Copyright © 2012 Pearson Education, Inc.


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
• As we've seen, the String class defines the
equals method to return true if two String objects
contain the same characters
• The designers of the String class have overridden
the equals method inherited from Object in favor
of a more useful version

Copyright © 2012 Pearson Education, Inc.


Case Study: Commission Employees
⬛ Inheritance hierarchy containing types of employees
in a company’s payroll application
⬛Commission employees are paid a percentage of
their sales
⬛Base-salaried commission employees receive a base
salary plus a percentage of their sales.

© Copyright 1992-2012 by Pearson Education, Inc. All Rights


Reserved.
Creating and Using a CommissionEmployee Class

Class CommissionEmployee extends class


Object (from package [Link]).

▪ CommissionEmployee inherits Object’s methods.


▪ If you don’t explicitly specify which class a new class extends, the class
extends Object implicitly.
Creating and Using a CommissionEmployee
Class (Cont.)
⬛Constructors are not inherited.
⬛The first task of a subclass constructor is to call its
direct superclass’s constructor explicitly or implicitly
▪ Ensures that the instance variables inherited from the
superclass are initialized properly.
⬛If the code does not include an explicit call to the
superclass constructor, Java implicitly calls the
superclass’s default or no-argument constructor.
⬛A class’s default constructor calls the superclass’s
default or no-argument constructor.
Creating and Using a CommissionEmployee Class
(Cont.)
⬛toString is one of the methods that every class inherits
directly or indirectly from class Object.
▪ Returns a String representing an object.
▪ Called implicitly whenever an object must be converted to a
String representation.

⬛ Class Object’s toString method returns a String that


includes the name of the object’s class.
▪ This is primarily a placeholder that can be overridden by a
subclass to specify an appropriate String representation.
Creating and Using a CommissionEmployee
Class (Cont.)
⬛To override a superclass method, a subclass must
declare a method with the same signature as the
superclass method

⬛ @Override annotation
▪ Indicates that a method should override a superclass method
with the same signature.
▪ If it does not, a compilation error occurs.
Case Study Part 2: Creating and Using a
BasePlus-CommissionEmployee Class
⬛ Class BasePlusCommissionEmployee contains a first name,
last name, social security number, gross sales amount,
commission rate and base salary.
▪ All but the base salary are in common with class CommissionEmployee.

⬛ Class BasePlusCommissionEmployee’s public services


include a constructor, and methods earnings, toString and get
and set for each instance variable
▪ Most of these are in common with class CommissionEmployee.
Class BasePlusCommissionEmployee does
not specify “extends Object”, Implicitly
extends Object.

BasePlusCommissionEmployee’s
constructor invokes class Object’s
default constructor implicitly.
Case Study Part 2: Creating and Using a BasePlus-
CommissionEmployee Class (Cont.)

⬛Much of BasePlusCommissionEmployee’s code is similar,


or identical, to that of CommissionEmployee.
⬛private instance variables firstName and lastName and
methods setFirstName, getFirstName, setLastName and
getLastName are identical.
▪ Both classes also contain corresponding get and set methods.
⬛ The constructors are almost identical
▪ BasePlusCommissionEmployee’s constructor also sets the base-
Salary.
⬛ The toString methods are nearly identical
▪ BasePlusCommissionEmployee’s toString also outputs instance
variable baseSalary
Case Study Part 2: Creating and Using a
BasePlus-CommissionEmployee Class (Cont.)
⬛ We literally copied CommissionEmployee’s code, pasted it into
BasePlusCommissionEmployee, then modified the new class to
include a base salary and methods that manipulate the base salary.
▪ This “copy-and-paste” approach is often error prone and time consuming.
▪ It spreads copies of the same code throughout a system, creating a code-
maintenance nightmare.
Case Study Part 3: Creating a CommissionEmployee–
BasePlusCommissionEmployee Inheritance Hierarchy
⬛Class BasePlusCommissionEmployee class extends class
CommissionEmployee
⬛A BasePlusCommissionEmployee object is a
CommissionEmployee
▪ Inheritance passes on class CommissionEmployee’s capabilities.
⬛Class BasePlusCommissionEmployee also has instance
variable baseSalary.
⬛Subclass BasePlusCommissionEmployee inherits
CommissionEmployee’s instance variables and methods
▪ Only the superclass’s public and protected members are directly accessible
in the subclass.
Case Study Part 3: Creating a CommissionEmployee–
BasePlusCommissionEmployee Inheritance Hierarchy (Cont.)

⬛Each subclass constructor must implicitly or explicitly call its superclass constructor
to initialize the instance variables inherited from the superclass.
▪ Superclass constructor call syntax—keyword super, followed by a set of
parentheses containing the superclass constructor arguments.
▪ Must be the first statement in the subclass constructor’s body.
⬛If the subclass constructor did not invoke the superclass’s constructor explicitly, Java
would attempt to invoke the superclass’s no-argument or default constructor.
▪ Class CommissionEmployee does not have such a constructor, so the compiler
would issue an error.
⬛You can explicitly use super() to call the superclass’s no-argument or default
constructor, but this is rarely done.
Case Study Part 4: CommissionEmployee–
BasePlusCommissionEmployee Inheritance Hierarchy Using
protected Instance Variables
⬛To enable a subclass to directly access superclass instance
variables, we can declare those members as protected in the
superclass.
⬛New CommissionEmployee class modified only lines 6–10 of
Fig. 9.4 as follows:
protected String firstName;
protected String lastName;
protected String socialSecurityNumber;
protected double grossSales;
protected double commissionRate;
⬛With protected instance variables, the subclass gets access
to the instance variables, but classes that are not subclasses
and classes that are not in the same package cannot access
these variables directly.
Case Study Part 4: CommissionEmployee–BasePlus-
CommissionEmployee Inheritance Hierarchy Using protected
Instance Variables (Cont.)

⬛ Class BasePlusCommissionEmployee (Fig. 9.9) extends the new


version of class CommissionEmployee with protected instance
variables.
▪ These variables are now protected members of
BasePlusCommissionEmployee.
⬛ If another class extends this version of class
BasePlusCommissionEmployee, the new subclass also can access
the protected members.
⬛ The source code in Fig. 9.9 (51 lines) is considerably shorter than
that in Fig. 9.6 (128 lines)
▪ Most of the functionality is now inherited from CommissionEmployee
▪ There is now only one copy of the functionality.
▪ Code is easier to maintain, modify and debug—the code related to a
commission employee exists only in class CommissionEmployee.
Case Study Part 4: CommissionEmployee–BasePlus-
CommissionEmployee Inheritance Hierarchy Using protected
Instance Variables (Cont.)

⬛Inheriting protected instance variables slightly


increases performance, because we can directly access
the variables in the subclass without incurring the
overhead of a set or get method call.

⬛In most cases, it’s better to use private instance


variables to encourage proper software engineering, and
leave code optimization issues to the compiler.
▪ Code will be easier to maintain, modify and debug.
Case Study Part 4: CommissionEmployee–BasePlus-
CommissionEmployee Inheritance Hierarchy Using protected Instance
Variables (Cont.)
⬛ Using protected instance variables creates several potential
problems.
⬛ The subclass object can set an inherited variable’s value directly

without using a set method.


▪ A subclass object can assign an invalid value to the variable
⬛ Subclass methods are more likely to be written so that they
depend on the superclass’s data implementation.
▪ Subclasses should depend only on the superclass services and not on the
superclass data implementation.
⬛ We may need to modify all the subclasses of the superclass if the
superclass implementation changes.
▪ You should be able to change the superclass implementation while still
providing the same services to the subclasses.
Case Study Part 5: CommissionEmployee–BasePlus-
CommissionEmployee Inheritance Hierarchy Using private Instance
Variables => BEST DESIGN

instance variables are declared as


private and public methods for
manipulating these are provided.
Case Study Part 5: CommissionEmployee–BasePlus-
CommissionEmployee Inheritance Hierarchy Using private Instance
Variables (Cont.)

⬛CommissionEmployee methods earnings and


toString use the class’s get methods to obtain the values
of its instance variables.
▪ If we decide to change the internal representation of the data (e.g.,
variable names) only the bodies of the get and set methods that
directly manipulate the instance variables will need to change.
▪ These changes occur solely within the superclass-—no changes to the
subclass are needed.
▪ Localizing the effects of changes like this is a good software
engineering practice.
⬛Subclass BasePlusCommissionEmployee inherits
CommissionEmployee’s non-private methods and can
access the private superclass members via those methods.
Case Study Part 5: CommissionEmployee–BasePlus-
CommissionEmployee Inheritance Hierarchy Using private
Instance Variables (Cont.)
Method earnings overrides class the
superclass’s earnings method.

calls CommissionEmployee’s
earnings method with
[Link]()

Good software engineering practice: If a method performs all or some of the


actions needed by another method, call that method rather than duplicate its code.
BasePlusCommissionEmployee’s toString method
overrides class CommissionEmployee’s toString method

The new version creates part of the String representation by


calling CommissionEmployee’s toString method with the
expression [Link]().
Abstract 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:

public abstract class Product


{
// class contents
}

Copyright © 2012 Pearson Education, Inc.


UML Inheritance Diagrams
A class hierarchy in UML notation

An Employee is a Person and so forth; hence


the arrows point up.
UML Inheritance Diagrams
⬛ Some details
of UML class
hierarchy
from previous
figure
Constructors in Subclasses
⬛Instantiating a subclass object begins a chain of constructor
calls
▪ The subclass constructor, before performing its own tasks, invokes its
direct superclass’s constructor
⬛If the superclass is derived from another class, the superclass
constructor invokes the constructor of the next class up the
hierarchy, and so on.
⬛The last constructor called in the chain is always class
Object’s constructor.
⬛Original subclass constructor’s body finishes executing last.

⬛Each superclass’s constructor manipulates the superclass


instance variables that the subclass object inherits.
Abstract Classes
• An abstract class often contains abstract methods
with no definitions (like an interface)

• Unlike an interface, the abstract modifier must be


applied to each abstract method

• Also, an abstract class typically contains non-


abstract methods with full definitions

• A class declared as abstract does not have to


contain abstract methods -- simply declaring it as
abstract makes it so

Copyright © 2012 Pearson Education, Inc.


Abstract 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


or static

• The use of abstract classes is an important element


of software design – it allows us to establish
common elements in a hierarchy that are too
general to instantiate

Copyright © 2012 Pearson Education, Inc.


Abstract

Copyright © 2012 Pearson


Education, Inc.
Abstract Class

Copyright © 2012 Pearson


Education, Inc.
Interface Hierarchies
• Inheritance can be applied to interfaces
• That is, one interface can be derived from another
interface
• The child interface inherits all abstract methods of
the parent
• A class implementing the child interface must define
all methods from both interfaces
• Class hierarchies and interface hierarchies are
distinct (they do not overlap)

Copyright © 2012 Pearson Education, Inc.


Abstract class vs Interface
• Type of methods: Interface can have only abstract methods. Abstract class can have
abstract and non-abstract methods. From Java 8, it can have default and static methods
also.
• Final Variables: Variables declared in a Java interface are by default final. An abstract class
may contain non-final variables.
• Type of variables: Abstract class can have final, non-final, static and non-static variables.
Interface has only static and final variables.
• Implementation: Abstract class can provide the implementation of interface. Interface can’t
provide the implementation of abstract class.
• Inheritance vs Abstraction: A Java interface can be implemented using keyword
“implements” and abstract class can be extended using keyword “extends”.
• Multiple implementation: An interface can extend another Java interface only, an abstract
class can extend another Java class and implement multiple Java interfaces.
• Accessibility of Data Members: Members of a Java interface are public by default. A Java
abstract class can have class members like private, protected, etc.

Copyright © 2012 Pearson


Education, Inc.
Abstract-Interface
Quick Check
What are some methods defined by the Object
class?

What is an abstract class?

Copyright © 2012 Pearson Education, Inc.


Quick Check
What are some methods defined by the Object
class?
String toString()
boolean equals(Object obj)
Object clone()

What is an abstract class?


An abstract class is a placeholder in the class
hierarchy, defining a general concept and gathering
elements common to all derived classes. An abstract
class cannot be instantiated.

Copyright © 2012 Pearson Education, Inc.


Outline

Creating Subclasses
Overriding Methods
Class Hierarchies
Visibility
Designing for Inheritance

Copyright © 2012 Pearson Education, Inc.


Visibility Revisited
• It's important to understand one subtle issue related
to inheritance and visibility
• All variables and methods of a parent class, even
private members, are inherited by its children
• As we've mentioned, private members cannot be
referenced by name in the child class
• However, private members inherited by child
classes exist and can be referenced indirectly

Copyright © 2012 Pearson Education, Inc.


Visibility Revisited
• Because the parent can refer to the private
member, the child can reference it indirectly using
its parent's methods

• The super reference can be used to refer to the


parent class, even if no object of the parent exists

• See [Link]
• See [Link]
• See [Link]

Copyright © 2012 Pearson Education, Inc.


//********************************************************************
// [Link] Author: Lewis/Loftus
//
// Represents an item of food. Used as the parent of a derived class
// to demonstrate indirect referencing.
//********************************************************************

public 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 numFatGrams, int numServings)
{
fatGrams = numFatGrams;
servings = numServings;
}

continue

Copyright © 2012 Pearson Education, Inc.


continue

//-----------------------------------------------------------------
// 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);
}
}

Copyright © 2012 Pearson Education, Inc.


//********************************************************************
// [Link] Author: Lewis/Loftus
//
// Represents a pizza, which is a food item. Used to demonstrate
// indirect referencing through inheritance.
//********************************************************************

public class Pizza extends FoodItem


{
//-----------------------------------------------------------------
// Sets up a pizza with the specified amount of fat (assumes
// eight servings).
//-----------------------------------------------------------------
public Pizza (int fatGrams)
{
super (fatGrams, 8);
}
}

Copyright © 2012 Pearson Education, Inc.


//********************************************************************
// [Link] Author: Lewis/Loftus
//
// Demonstrates indirect access to inherited private members.
//********************************************************************

public class FoodAnalyzer


{
//-----------------------------------------------------------------
// Instantiates a Pizza object and prints its calories per
// serving.
//-----------------------------------------------------------------
public static void main (String[] args)
{
Pizza special = new Pizza (275);

[Link] ("Calories per serving: " +


[Link]());
}
}

Copyright © 2012 Pearson Education, Inc.


//********************************************************************
Output
// [Link] Author: Lewis/Loftus
// Calories per serving: 309
// Demonstrates indirect access to inherited private members.
//********************************************************************

public class FoodAnalyzer


{
//-----------------------------------------------------------------
// Instantiates a Pizza object and prints its calories per
// serving.
//-----------------------------------------------------------------
public static void main (String[] args)
{
Pizza special = new Pizza (275);

[Link] ("Calories per serving: " +


[Link]());
}
}

Copyright © 2012 Pearson Education, Inc.


Outline

Creating Subclasses
Overriding Methods
Class Hierarchies
Visibility
Designing for Inheritance

Copyright © 2012 Pearson Education, Inc.


Designing for Inheritance
• As we've discussed, taking the time to create a
good software design reaps long-term benefits
• Inheritance issues are an important part of an
object-oriented design
• Properly designed inheritance relationships can
contribute greatly to the elegance, maintainability,
and reuse of the software
• Let's summarize some of the issues regarding
inheritance that relate to a good software design

Copyright © 2012 Pearson Education, Inc.


Inheritance Design Issues
• Every derivation should be an is-a relationship
• Think about the potential future of a class hierarchy,
and design classes to be reusable and flexible
• Find common characteristics of classes and push
them as high in the class hierarchy as appropriate
• Override methods as appropriate to tailor or change
the functionality of a child
• Add new variables to children, but don't redefine
(shadow) inherited variables

Copyright © 2012 Pearson Education, Inc.


Inheritance Design Issues
• Allow each class to manage its own data; use the
super reference to invoke the parent's constructor
to set up its data
• Override general methods such as toString and
equals with appropriate definitions

• Use abstract classes to represent general concepts


that derived classes have in common
• Use visibility modifiers carefully to provide needed
access without violating encapsulation

Copyright © 2012 Pearson Education, Inc.


Restricting Inheritance
• !!! If the final modifier is applied to a method, that
method cannot be overridden in any derived
classes

• This is a design issue. In most of your programs you


don’t need to do such things (usually)

Copyright © 2012 Pearson Education, Inc.

You might also like