SlideShare a Scribd company logo
INHERITANCE
Chapter 10
INHERITANCE
 Mechanism for enhancing existing classes
 You need to implement a new class
 You have an existing class that represents a more
general concept is already available.
 New class can inherit from the existing class.
 Example
 BankAccount
 SavingsAccount
 Most of the methods of bank account apply to savings
account
 You need additional methods.
 In savings account you only specify new methods.
INHERITANCE
 More generic form is super class.
 Class that inherits from super class is subclass.
 One advantage – code reuse
public class SavingsAccount extends BankAccount
{
public void addInterest()
{
double interest = getBalance() *
interestRate / 100;
deposit(interest);
}
private double interestRate;
}
INHERITANCE
 BankAccount will have the methods
 deposit( )
 withdraw( )
 getBalance( )
 SavingsAccount will have the methods
 deposit( )
 withdraw( )
 getBalance( )
 addInterest( )
HIERARCHIES
Archosaurs
Thecodonts Pterosaurs Dinosaurs
Saurischians Ornithischians
Crocodilians
Every class extends the Object
class either directly or indirectly
An Inheritance Diagram
RELOOK AT SAVINGSACCOUNT
public class SavingsAccount extends BankAccount
{
public void addInterest()
{
double interest = getBalance() *
interestRate /
100;
deposit(interest);
}
private double interestRate;
}
• Encapsulation: addInterest calls
getBalance rather than updating the
balance field of the superclass (field is
private)
• Note that addInterest calls
getBalance without specifying an implicit
parameter (the calls apply to the same object)
An Introduction to Inheritance
BigJavabyCayHorstmann
Copyright©2008byJohnWiley&Sons.Allrights
reserved.
SavingsAccount object inherits the balance
instance field from BankAccount, and gains one
additional instance field: interestRate:
Layout of a Subclass Object
CHECK
 If the class Manager extends the class Employee,
which class is the superclass and which is the
subclass?
• Consider a bank that offers its customers the following account
types:
1. Checking account: no interest; small number of free
transactions per month, additional transactions are
charged a small fee
2. Savings account: earns interest that compounds
monthly
• Inheritance hierarchy:
• All bank accounts support the getBalance method
• All bank accounts support the deposit and withdraw
methods, but the implementations differ
• Checking account needs a method deductFees; savings
account needs a method addInterest
Hierarchy of Bank Accounts
• Override method:
• Supply a different implementation of a method that
exists in the superclass
• Must have same signature (same name and same
parameter types)
• If method is applied to an object of the subclass
type, the overriding method is executed
• Inherit method:
• Don't supply a new implementation of a method that
exists in superclass
•Superclass method can be applied to the
subclass objects
• Add method:
• Supply a new method that doesn't exist in the
superclass
• New method can be applied only to subclass
objects
Inheriting Methods
• Can't override fields
• Inherit field: All fields from the superclass are
automatically inherited
• Add field: Supply a new field that doesn't exist
in the superclass
• What if you define a new field with the same
name as a superclass field?
• Each object would have two instance
fields of the same name
• Fields can hold different values
• Legal but extremely undesirable
Inheriting Instance Fields
• Consider deposit method of
CheckingAccount
public void deposit(double amount)
{
transactionCount++;
// now add amount to balance
. . .
}
• Can't just add amount to balance
• balance is a private field of the superclass
• A subclass has no access to private fields of its
superclass
• Subclass must use public interface
Inherited Fields are Private
• Can't just call
deposit(amount)
in deposit method of CheckingAccount
• That is the same as
this.deposit(amount)
• Calls the same method
• Instead, invoke superclass method
super.deposit(amount)
• Now calls deposit method of BankAccount
class
Invoking a Superclass Method
• Complete method:
public void deposit(double amount)
{
transactionCount++;
// Now add amount to balance
super.deposit(amount);
}
Invoking a Superclass Method
SUBCLASS CONSTRUCTOR
 You write a constructor in the subclass
 Call the super class constructor
 Use the word super
 Must be the first statement of the subclass constructor
• If subclass constructor doesn't call superclass
constructor, default superclass constructor is used
•Default constructor: constructor with no
parameters
•If all constructors of the superclass
require parameters, then the compiler
reports an error
Subclass Construction
• Ok to convert subclass reference to superclass
reference
SavingsAccount collegeFund = new
SavingsAccount(10);
BankAccount anAccount =
collegeFund;
Object anObject = collegeFund;
• The three object references stored in
collegeFund, anAccount, and
anObject all refer to the same object of type
SavingsAccount
Converting Between Subclass and Superclass
Types
Converting Between Subclass and Superclass Types
• Superclass references don't know the full story:
anAccount.deposit(1000); // OK
anAccount.addInterest();
// No--not a method of the class
to which anAccount
belongs
• When you convert between a subclass object to its
superclass type:
• The value of the reference stays the same – it is
the memory location of the object
• But, less information is known about the object
Converting Between Subclass and Superclass
Types
• Why would anyone want to know less about an object?
• Reuse code that knows about the superclass but not the subclass:
public void transfer(double amount, BankAccount other)
{
withdraw(amount);
other.deposit(amount);
}
Can be used to transfer money from any type of
BankAccount
Converting Between Subclass and Superclass Types (cont.)
• Occasionally you need to convert from a superclass reference
to a subclass reference
BankAccount anAccount = (BankAccount)
anObject;
• This cast is dangerous: if you are wrong, an exception is
thrown
• Solution: use the instanceof operator
• instanceof: tests whether an object belongs to a
particular type
if (anObject instanceof BankAccount)
{
BankAccount anAccount = (BankAccount)
anObject;
. . .
}
Converting Between Subclass and Superclass Types
• In Java, type of a variable doesn't completely
determine type of object to which it refers
BankAccount aBankAccount = new
SavingsAccount(1000); // aBankAccount
holds a reference to a SavingsAccount
• Method calls are determined by type of actual object, not
type of object reference
BankAccount anAccount = new
CheckingAccount();
anAccount.deposit(1000); // Calls
"deposit" from
CheckingAccount
• Compiler needs to check that only legal methods are
invoked Object anObject = new
BankAccount();
anObject.deposit(1000); // Wrong!
Polymorphism
• Polymorphism: ability to refer to objects of multiple types with varying
behavior
• Polymorphism at work:
public void transfer(double amount, BankAccount
other)
{
withdraw(amount); // Shortcut for
this.withdraw(amount)
other.deposit(amount);
}
• Depending on types of amount and other, different versions of
withdraw and deposit are called
Polymorphism
• Java has four levels of controlling access to fields, methods, and
classes:
• public access
oCan be accessed by methods of all classes
• private access
oCan be accessed only by the methods of their own
class
• protected access
• package access
oThe default, when no access modifier is given
oCan be accessed by all classes in the same
package
oGood default for classes, but extremely
unfortunate for fields
Access Control
Access Levels
Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
no
modifier
Y Y N N
private Y N N N
The following table shows the access to members
permitted by each modifier.
http://java.sun.com/docs/books/tutorial/java/javaOO/accesscontrol.html
• All classes defined without an explicit extends clause automatically extend Object
Object: The Cosmic Superclass

More Related Content

PPTX
Java tutorial part 4
Mumbai Academisc
 
PPTX
Is2215 lecture4 student (1)
dannygriff1
 
PPTX
Java Tutorial Lab 1
Berk Soysal
 
PPTX
Session 09 - OOPS
SiddharthSelenium
 
PPTX
Exception handling
James Wong
 
PPTX
Python language data types
James Wong
 
PPT
Database concepts
James Wong
 
Java tutorial part 4
Mumbai Academisc
 
Is2215 lecture4 student (1)
dannygriff1
 
Java Tutorial Lab 1
Berk Soysal
 
Session 09 - OOPS
SiddharthSelenium
 
Exception handling
James Wong
 
Python language data types
James Wong
 
Database concepts
James Wong
 

Viewers also liked (16)

PPT
Xml stylus studio
James Wong
 
PPT
Crypto theory practice
James Wong
 
PPTX
Smm and caching
James Wong
 
PPTX
Crypto passport authentication
James Wong
 
PPT
Stack squeues lists
James Wong
 
PPT
Information retrieval
James Wong
 
PPTX
Python your new best friend
James Wong
 
PPT
Stack queue
James Wong
 
PPTX
Decision tree
James Wong
 
PPTX
Decision analysis
James Wong
 
PPTX
Key exchange in crypto
James Wong
 
PPT
Exception
James Wong
 
PPT
Big data
James Wong
 
PPTX
Rest api to integrate with your site
James Wong
 
PPT
Data race
James Wong
 
PPT
Multi threaded rtos
James Wong
 
Xml stylus studio
James Wong
 
Crypto theory practice
James Wong
 
Smm and caching
James Wong
 
Crypto passport authentication
James Wong
 
Stack squeues lists
James Wong
 
Information retrieval
James Wong
 
Python your new best friend
James Wong
 
Stack queue
James Wong
 
Decision tree
James Wong
 
Decision analysis
James Wong
 
Key exchange in crypto
James Wong
 
Exception
James Wong
 
Big data
James Wong
 
Rest api to integrate with your site
James Wong
 
Data race
James Wong
 
Multi threaded rtos
James Wong
 
Ad

Similar to Inheritance (20)

PPT
ch10.ppt
ssuser8f8b7a
 
PPT
Synapseindia strcture of dotnet development part 2
Synapseindiappsdevelopment
 
PPTX
Java 102 intro to object-oriented programming in java
agorolabs
 
PPTX
Lec-21-Classes and Object Orientation.pptx
resoj26651
 
PPTX
class as the basis.pptx
Epsiba1
 
PPT
Lecture 2 inheritance
Nada G.Youssef
 
PDF
Inheritance
FALLEE31188
 
PPTX
CiIC4010-chapter-2-f17
BienvenidoVelezUPR
 
PPTX
Classes, Objects and Method - Object Oriented Programming with Java
Radhika Talaviya
 
PPT
Classes2
phanleson
 
PPTX
inheritance and polymorphism
KarthigaGunasekaran1
 
PDF
Object Oriented PHP - PART-1
Jalpesh Vasa
 
PPT
5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt
AshwathGupta
 
PPTX
Object Oriented Programming C#
Muhammad Younis
 
PPTX
Inheritance
Daman Toor
 
PPTX
Icom4015 lecture7-f16
BienvenidoVelezUPR
 
PPT
JAVA Polymorphism
Mahi Mca
 
PPT
Chapter 12
Terry Yoast
 
PPT
04inherit
Waheed Warraich
 
PPT
Lecture d-inheritance
Tej Kiran
 
ch10.ppt
ssuser8f8b7a
 
Synapseindia strcture of dotnet development part 2
Synapseindiappsdevelopment
 
Java 102 intro to object-oriented programming in java
agorolabs
 
Lec-21-Classes and Object Orientation.pptx
resoj26651
 
class as the basis.pptx
Epsiba1
 
Lecture 2 inheritance
Nada G.Youssef
 
Inheritance
FALLEE31188
 
CiIC4010-chapter-2-f17
BienvenidoVelezUPR
 
Classes, Objects and Method - Object Oriented Programming with Java
Radhika Talaviya
 
Classes2
phanleson
 
inheritance and polymorphism
KarthigaGunasekaran1
 
Object Oriented PHP - PART-1
Jalpesh Vasa
 
5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt
AshwathGupta
 
Object Oriented Programming C#
Muhammad Younis
 
Inheritance
Daman Toor
 
Icom4015 lecture7-f16
BienvenidoVelezUPR
 
JAVA Polymorphism
Mahi Mca
 
Chapter 12
Terry Yoast
 
04inherit
Waheed Warraich
 
Lecture d-inheritance
Tej Kiran
 
Ad

More from James Wong (20)

PPT
Recursion
James Wong
 
PPTX
Business analytics and data mining
James Wong
 
PPTX
Data mining and knowledge discovery
James Wong
 
PPTX
Cache recap
James Wong
 
PPTX
Big picture of data mining
James Wong
 
PPTX
How analysis services caching works
James Wong
 
PPTX
Optimizing shared caches in chip multiprocessors
James Wong
 
PPTX
Directory based cache coherence
James Wong
 
PPT
Abstract data types
James Wong
 
PPTX
Abstraction file
James Wong
 
PPTX
Hardware managed cache
James Wong
 
PPTX
Object model
James Wong
 
PPT
Abstract class
James Wong
 
PPTX
Object oriented analysis
James Wong
 
PPTX
Concurrency with java
James Wong
 
PPTX
Data structures and algorithms
James Wong
 
PPTX
Cobol, lisp, and python
James Wong
 
PPTX
Api crash
James Wong
 
PPTX
Learning python
James Wong
 
PPTX
Programming for engineers in python
James Wong
 
Recursion
James Wong
 
Business analytics and data mining
James Wong
 
Data mining and knowledge discovery
James Wong
 
Cache recap
James Wong
 
Big picture of data mining
James Wong
 
How analysis services caching works
James Wong
 
Optimizing shared caches in chip multiprocessors
James Wong
 
Directory based cache coherence
James Wong
 
Abstract data types
James Wong
 
Abstraction file
James Wong
 
Hardware managed cache
James Wong
 
Object model
James Wong
 
Abstract class
James Wong
 
Object oriented analysis
James Wong
 
Concurrency with java
James Wong
 
Data structures and algorithms
James Wong
 
Cobol, lisp, and python
James Wong
 
Api crash
James Wong
 
Learning python
James Wong
 
Programming for engineers in python
James Wong
 

Recently uploaded (20)

PDF
How ETL Control Logic Keeps Your Pipelines Safe and Reliable.pdf
Stryv Solutions Pvt. Ltd.
 
PPTX
Simple and concise overview about Quantum computing..pptx
mughal641
 
PDF
Research-Fundamentals-and-Topic-Development.pdf
ayesha butalia
 
PPTX
Agile Chennai 18-19 July 2025 | Emerging patterns in Agentic AI by Bharani Su...
AgileNetwork
 
PDF
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
PDF
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
PDF
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
PDF
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
PDF
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
PDF
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
PPTX
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
PPTX
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
PDF
OFFOFFBOX™ – A New Era for African Film | Startup Presentation
ambaicciwalkerbrian
 
PPTX
Introduction to Flutter by Ayush Desai.pptx
ayushdesai204
 
PPTX
The Future of AI & Machine Learning.pptx
pritsen4700
 
PPTX
Agile Chennai 18-19 July 2025 Ideathon | AI Powered Microfinance Literacy Gui...
AgileNetwork
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PPTX
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
PPTX
Applied-Statistics-Mastering-Data-Driven-Decisions.pptx
parmaryashparmaryash
 
PDF
Responsible AI and AI Ethics - By Sylvester Ebhonu
Sylvester Ebhonu
 
How ETL Control Logic Keeps Your Pipelines Safe and Reliable.pdf
Stryv Solutions Pvt. Ltd.
 
Simple and concise overview about Quantum computing..pptx
mughal641
 
Research-Fundamentals-and-Topic-Development.pdf
ayesha butalia
 
Agile Chennai 18-19 July 2025 | Emerging patterns in Agentic AI by Bharani Su...
AgileNetwork
 
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
OFFOFFBOX™ – A New Era for African Film | Startup Presentation
ambaicciwalkerbrian
 
Introduction to Flutter by Ayush Desai.pptx
ayushdesai204
 
The Future of AI & Machine Learning.pptx
pritsen4700
 
Agile Chennai 18-19 July 2025 Ideathon | AI Powered Microfinance Literacy Gui...
AgileNetwork
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
Applied-Statistics-Mastering-Data-Driven-Decisions.pptx
parmaryashparmaryash
 
Responsible AI and AI Ethics - By Sylvester Ebhonu
Sylvester Ebhonu
 

Inheritance

  • 2. INHERITANCE  Mechanism for enhancing existing classes  You need to implement a new class  You have an existing class that represents a more general concept is already available.  New class can inherit from the existing class.  Example  BankAccount  SavingsAccount  Most of the methods of bank account apply to savings account  You need additional methods.  In savings account you only specify new methods.
  • 3. INHERITANCE  More generic form is super class.  Class that inherits from super class is subclass.  One advantage – code reuse public class SavingsAccount extends BankAccount { public void addInterest() { double interest = getBalance() * interestRate / 100; deposit(interest); } private double interestRate; }
  • 4. INHERITANCE  BankAccount will have the methods  deposit( )  withdraw( )  getBalance( )  SavingsAccount will have the methods  deposit( )  withdraw( )  getBalance( )  addInterest( )
  • 6. Every class extends the Object class either directly or indirectly An Inheritance Diagram
  • 7. RELOOK AT SAVINGSACCOUNT public class SavingsAccount extends BankAccount { public void addInterest() { double interest = getBalance() * interestRate / 100; deposit(interest); } private double interestRate; }
  • 8. • Encapsulation: addInterest calls getBalance rather than updating the balance field of the superclass (field is private) • Note that addInterest calls getBalance without specifying an implicit parameter (the calls apply to the same object) An Introduction to Inheritance
  • 9. BigJavabyCayHorstmann Copyright©2008byJohnWiley&Sons.Allrights reserved. SavingsAccount object inherits the balance instance field from BankAccount, and gains one additional instance field: interestRate: Layout of a Subclass Object
  • 10. CHECK  If the class Manager extends the class Employee, which class is the superclass and which is the subclass?
  • 11. • Consider a bank that offers its customers the following account types: 1. Checking account: no interest; small number of free transactions per month, additional transactions are charged a small fee 2. Savings account: earns interest that compounds monthly • Inheritance hierarchy: • All bank accounts support the getBalance method • All bank accounts support the deposit and withdraw methods, but the implementations differ • Checking account needs a method deductFees; savings account needs a method addInterest Hierarchy of Bank Accounts
  • 12. • Override method: • Supply a different implementation of a method that exists in the superclass • Must have same signature (same name and same parameter types) • If method is applied to an object of the subclass type, the overriding method is executed • Inherit method: • Don't supply a new implementation of a method that exists in superclass •Superclass method can be applied to the subclass objects • Add method: • Supply a new method that doesn't exist in the superclass • New method can be applied only to subclass objects Inheriting Methods
  • 13. • Can't override fields • Inherit field: All fields from the superclass are automatically inherited • Add field: Supply a new field that doesn't exist in the superclass • What if you define a new field with the same name as a superclass field? • Each object would have two instance fields of the same name • Fields can hold different values • Legal but extremely undesirable Inheriting Instance Fields
  • 14. • Consider deposit method of CheckingAccount public void deposit(double amount) { transactionCount++; // now add amount to balance . . . } • Can't just add amount to balance • balance is a private field of the superclass • A subclass has no access to private fields of its superclass • Subclass must use public interface Inherited Fields are Private
  • 15. • Can't just call deposit(amount) in deposit method of CheckingAccount • That is the same as this.deposit(amount) • Calls the same method • Instead, invoke superclass method super.deposit(amount) • Now calls deposit method of BankAccount class Invoking a Superclass Method
  • 16. • Complete method: public void deposit(double amount) { transactionCount++; // Now add amount to balance super.deposit(amount); } Invoking a Superclass Method
  • 17. SUBCLASS CONSTRUCTOR  You write a constructor in the subclass  Call the super class constructor  Use the word super  Must be the first statement of the subclass constructor
  • 18. • If subclass constructor doesn't call superclass constructor, default superclass constructor is used •Default constructor: constructor with no parameters •If all constructors of the superclass require parameters, then the compiler reports an error Subclass Construction
  • 19. • Ok to convert subclass reference to superclass reference SavingsAccount collegeFund = new SavingsAccount(10); BankAccount anAccount = collegeFund; Object anObject = collegeFund; • The three object references stored in collegeFund, anAccount, and anObject all refer to the same object of type SavingsAccount Converting Between Subclass and Superclass Types
  • 20. Converting Between Subclass and Superclass Types
  • 21. • Superclass references don't know the full story: anAccount.deposit(1000); // OK anAccount.addInterest(); // No--not a method of the class to which anAccount belongs • When you convert between a subclass object to its superclass type: • The value of the reference stays the same – it is the memory location of the object • But, less information is known about the object Converting Between Subclass and Superclass Types
  • 22. • Why would anyone want to know less about an object? • Reuse code that knows about the superclass but not the subclass: public void transfer(double amount, BankAccount other) { withdraw(amount); other.deposit(amount); } Can be used to transfer money from any type of BankAccount Converting Between Subclass and Superclass Types (cont.)
  • 23. • Occasionally you need to convert from a superclass reference to a subclass reference BankAccount anAccount = (BankAccount) anObject; • This cast is dangerous: if you are wrong, an exception is thrown • Solution: use the instanceof operator • instanceof: tests whether an object belongs to a particular type if (anObject instanceof BankAccount) { BankAccount anAccount = (BankAccount) anObject; . . . } Converting Between Subclass and Superclass Types
  • 24. • In Java, type of a variable doesn't completely determine type of object to which it refers BankAccount aBankAccount = new SavingsAccount(1000); // aBankAccount holds a reference to a SavingsAccount • Method calls are determined by type of actual object, not type of object reference BankAccount anAccount = new CheckingAccount(); anAccount.deposit(1000); // Calls "deposit" from CheckingAccount • Compiler needs to check that only legal methods are invoked Object anObject = new BankAccount(); anObject.deposit(1000); // Wrong! Polymorphism
  • 25. • Polymorphism: ability to refer to objects of multiple types with varying behavior • Polymorphism at work: public void transfer(double amount, BankAccount other) { withdraw(amount); // Shortcut for this.withdraw(amount) other.deposit(amount); } • Depending on types of amount and other, different versions of withdraw and deposit are called Polymorphism
  • 26. • Java has four levels of controlling access to fields, methods, and classes: • public access oCan be accessed by methods of all classes • private access oCan be accessed only by the methods of their own class • protected access • package access oThe default, when no access modifier is given oCan be accessed by all classes in the same package oGood default for classes, but extremely unfortunate for fields Access Control
  • 27. Access Levels Modifier Class Package Subclass World public Y Y Y Y protected Y Y Y N no modifier Y Y N N private Y N N N The following table shows the access to members permitted by each modifier. http://java.sun.com/docs/books/tutorial/java/javaOO/accesscontrol.html
  • 28. • All classes defined without an explicit extends clause automatically extend Object Object: The Cosmic Superclass