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

Viewers also liked

Api crash
Api crashApi crash
Api crash
Tony Nguyen
 
How analysis services caching works
How analysis services caching worksHow analysis services caching works
How analysis services caching works
Harry Potter
 
Python language data types
Python language data typesPython language data types
Python language data types
Tony Nguyen
 
How to build a rest api
How to build a rest apiHow to build a rest api
How to build a rest api
Tony Nguyen
 
Python your new best friend
Python your new best friendPython your new best friend
Python your new best friend
Luis Goldster
 
Abstract class
Abstract classAbstract class
Abstract class
Harry Potter
 
Abstraction file
Abstraction fileAbstraction file
Abstraction file
Fraboni Ec
 
Object oriented programming-with_java
Object oriented programming-with_javaObject oriented programming-with_java
Object oriented programming-with_java
Tony Nguyen
 
Api crash
Api crashApi crash
Api crash
Fraboni Ec
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
Luis Goldster
 
Learning python
Learning pythonLearning python
Learning python
Harry Potter
 
Hardware managed cache
Hardware managed cacheHardware managed cache
Hardware managed cache
Fraboni Ec
 
Python language data types
Python language data typesPython language data types
Python language data types
Harry Potter
 
Encapsulation anonymous class
Encapsulation anonymous classEncapsulation anonymous class
Encapsulation anonymous class
Harry Potter
 
Hardware managed cache
Hardware managed cacheHardware managed cache
Hardware managed cache
Harry Potter
 
Hardware managed cache
Hardware managed cacheHardware managed cache
Hardware managed cache
Tony Nguyen
 
Extending burp with python
Extending burp with pythonExtending burp with python
Extending burp with python
Tony Nguyen
 
Abstraction file
Abstraction fileAbstraction file
Abstraction file
Tony Nguyen
 
Smm and caching
Smm and cachingSmm and caching
Smm and caching
Tony Nguyen
 
Directory based cache coherence
Directory based cache coherenceDirectory based cache coherence
Directory based cache coherence
Harry Potter
 

Viewers also liked (20)

Api crash
Api crashApi crash
Api crash
 
How analysis services caching works
How analysis services caching worksHow analysis services caching works
How analysis services caching works
 
Python language data types
Python language data typesPython language data types
Python language data types
 
How to build a rest api
How to build a rest apiHow to build a rest api
How to build a rest api
 
Python your new best friend
Python your new best friendPython your new best friend
Python your new best friend
 
Abstract class
Abstract classAbstract class
Abstract class
 
Abstraction file
Abstraction fileAbstraction file
Abstraction file
 
Object oriented programming-with_java
Object oriented programming-with_javaObject oriented programming-with_java
Object oriented programming-with_java
 
Api crash
Api crashApi crash
Api crash
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Learning python
Learning pythonLearning python
Learning python
 
Hardware managed cache
Hardware managed cacheHardware managed cache
Hardware managed cache
 
Python language data types
Python language data typesPython language data types
Python language data types
 
Encapsulation anonymous class
Encapsulation anonymous classEncapsulation anonymous class
Encapsulation anonymous class
 
Hardware managed cache
Hardware managed cacheHardware managed cache
Hardware managed cache
 
Hardware managed cache
Hardware managed cacheHardware managed cache
Hardware managed cache
 
Extending burp with python
Extending burp with pythonExtending burp with python
Extending burp with python
 
Abstraction file
Abstraction fileAbstraction file
Abstraction file
 
Smm and caching
Smm and cachingSmm and caching
Smm and caching
 
Directory based cache coherence
Directory based cache coherenceDirectory based cache coherence
Directory based cache coherence
 

Similar to Inheritance

ch10.ppt
ch10.pptch10.ppt
ch10.ppt
ssuser8f8b7a
 
Synapseindia strcture of dotnet development part 2
Synapseindia strcture of dotnet development part 2Synapseindia strcture of dotnet development part 2
Synapseindia strcture of dotnet development part 2
Synapseindiappsdevelopment
 
Java 102 intro to object-oriented programming in java
Java 102   intro to object-oriented programming in javaJava 102   intro to object-oriented programming in java
Java 102 intro to object-oriented programming in java
agorolabs
 
class as the basis.pptx
class as the basis.pptxclass as the basis.pptx
class as the basis.pptx
Epsiba1
 
Lecture 2 inheritance
Lecture 2    inheritanceLecture 2    inheritance
Lecture 2 inheritance
Nada G.Youssef
 
Inheritance
InheritanceInheritance
Inheritance
FALLEE31188
 
CiIC4010-chapter-2-f17
CiIC4010-chapter-2-f17CiIC4010-chapter-2-f17
CiIC4010-chapter-2-f17
BienvenidoVelezUPR
 
Classes, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with JavaClasses, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with Java
Radhika Talaviya
 
Classes2
Classes2Classes2
Classes2
phanleson
 
inheritance and polymorphism
inheritance and polymorphisminheritance and polymorphism
inheritance and polymorphism
KarthigaGunasekaran1
 
Object Oriented PHP - PART-1
Object Oriented PHP - PART-1Object Oriented PHP - PART-1
Object Oriented PHP - PART-1
Jalpesh Vasa
 
5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt
5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt
5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt
AshwathGupta
 
Object Oriented Programming C#
Object Oriented Programming C#Object Oriented Programming C#
Object Oriented Programming C#
Muhammad Younis
 
Inheritance
InheritanceInheritance
Inheritance
Daman Toor
 
Icom4015 lecture7-f16
Icom4015 lecture7-f16Icom4015 lecture7-f16
Icom4015 lecture7-f16
BienvenidoVelezUPR
 
JAVA Polymorphism
JAVA PolymorphismJAVA Polymorphism
JAVA Polymorphism
Mahi Mca
 
Chapter 12
Chapter 12Chapter 12
Chapter 12
Terry Yoast
 
04inherit
04inherit04inherit
04inherit
Waheed Warraich
 
Lecture d-inheritance
Lecture d-inheritanceLecture d-inheritance
Lecture d-inheritance
Tej Kiran
 
Ap Power Point Chpt4
Ap Power Point Chpt4Ap Power Point Chpt4
Ap Power Point Chpt4
dplunkett
 

Similar to Inheritance (20)

ch10.ppt
ch10.pptch10.ppt
ch10.ppt
 
Synapseindia strcture of dotnet development part 2
Synapseindia strcture of dotnet development part 2Synapseindia strcture of dotnet development part 2
Synapseindia strcture of dotnet development part 2
 
Java 102 intro to object-oriented programming in java
Java 102   intro to object-oriented programming in javaJava 102   intro to object-oriented programming in java
Java 102 intro to object-oriented programming in java
 
class as the basis.pptx
class as the basis.pptxclass as the basis.pptx
class as the basis.pptx
 
Lecture 2 inheritance
Lecture 2    inheritanceLecture 2    inheritance
Lecture 2 inheritance
 
Inheritance
InheritanceInheritance
Inheritance
 
CiIC4010-chapter-2-f17
CiIC4010-chapter-2-f17CiIC4010-chapter-2-f17
CiIC4010-chapter-2-f17
 
Classes, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with JavaClasses, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with Java
 
Classes2
Classes2Classes2
Classes2
 
inheritance and polymorphism
inheritance and polymorphisminheritance and polymorphism
inheritance and polymorphism
 
Object Oriented PHP - PART-1
Object Oriented PHP - PART-1Object Oriented PHP - PART-1
Object Oriented PHP - PART-1
 
5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt
5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt
5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt
 
Object Oriented Programming C#
Object Oriented Programming C#Object Oriented Programming C#
Object Oriented Programming C#
 
Inheritance
InheritanceInheritance
Inheritance
 
Icom4015 lecture7-f16
Icom4015 lecture7-f16Icom4015 lecture7-f16
Icom4015 lecture7-f16
 
JAVA Polymorphism
JAVA PolymorphismJAVA Polymorphism
JAVA Polymorphism
 
Chapter 12
Chapter 12Chapter 12
Chapter 12
 
04inherit
04inherit04inherit
04inherit
 
Lecture d-inheritance
Lecture d-inheritanceLecture d-inheritance
Lecture d-inheritance
 
Ap Power Point Chpt4
Ap Power Point Chpt4Ap Power Point Chpt4
Ap Power Point Chpt4
 

More from Fraboni Ec

Hardware multithreading
Hardware multithreadingHardware multithreading
Hardware multithreading
Fraboni Ec
 
Lisp
LispLisp
What is simultaneous multithreading
What is simultaneous multithreadingWhat is simultaneous multithreading
What is simultaneous multithreading
Fraboni Ec
 
Directory based cache coherence
Directory based cache coherenceDirectory based cache coherence
Directory based cache coherence
Fraboni Ec
 
Business analytics and data mining
Business analytics and data miningBusiness analytics and data mining
Business analytics and data mining
Fraboni Ec
 
Big picture of data mining
Big picture of data miningBig picture of data mining
Big picture of data mining
Fraboni Ec
 
Data mining and knowledge discovery
Data mining and knowledge discoveryData mining and knowledge discovery
Data mining and knowledge discovery
Fraboni Ec
 
Cache recap
Cache recapCache recap
Cache recap
Fraboni Ec
 
How analysis services caching works
How analysis services caching worksHow analysis services caching works
How analysis services caching works
Fraboni Ec
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
Fraboni Ec
 
Cobol, lisp, and python
Cobol, lisp, and pythonCobol, lisp, and python
Cobol, lisp, and python
Fraboni Ec
 
Abstract data types
Abstract data typesAbstract data types
Abstract data types
Fraboni Ec
 
Optimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsOptimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessors
Fraboni Ec
 
Object model
Object modelObject model
Object model
Fraboni Ec
 
Object oriented analysis
Object oriented analysisObject oriented analysis
Object oriented analysis
Fraboni Ec
 
Abstract class
Abstract classAbstract class
Abstract class
Fraboni Ec
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
Fraboni Ec
 
Extending burp with python
Extending burp with pythonExtending burp with python
Extending burp with python
Fraboni Ec
 
Learning python
Learning pythonLearning python
Learning python
Fraboni Ec
 
Programming for engineers in python
Programming for engineers in pythonProgramming for engineers in python
Programming for engineers in python
Fraboni Ec
 

More from Fraboni Ec (20)

Hardware multithreading
Hardware multithreadingHardware multithreading
Hardware multithreading
 
Lisp
LispLisp
Lisp
 
What is simultaneous multithreading
What is simultaneous multithreadingWhat is simultaneous multithreading
What is simultaneous multithreading
 
Directory based cache coherence
Directory based cache coherenceDirectory based cache coherence
Directory based cache coherence
 
Business analytics and data mining
Business analytics and data miningBusiness analytics and data mining
Business analytics and data mining
 
Big picture of data mining
Big picture of data miningBig picture of data mining
Big picture of data mining
 
Data mining and knowledge discovery
Data mining and knowledge discoveryData mining and knowledge discovery
Data mining and knowledge discovery
 
Cache recap
Cache recapCache recap
Cache recap
 
How analysis services caching works
How analysis services caching worksHow analysis services caching works
How analysis services caching works
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
Cobol, lisp, and python
Cobol, lisp, and pythonCobol, lisp, and python
Cobol, lisp, and python
 
Abstract data types
Abstract data typesAbstract data types
Abstract data types
 
Optimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsOptimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessors
 
Object model
Object modelObject model
Object model
 
Object oriented analysis
Object oriented analysisObject oriented analysis
Object oriented analysis
 
Abstract class
Abstract classAbstract class
Abstract class
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Extending burp with python
Extending burp with pythonExtending burp with python
Extending burp with python
 
Learning python
Learning pythonLearning python
Learning python
 
Programming for engineers in python
Programming for engineers in pythonProgramming for engineers in python
Programming for engineers in python
 

Recently uploaded

Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 
System Design Case Study: Building a Scalable E-Commerce Platform - Hiike
System Design Case Study: Building a Scalable E-Commerce Platform - HiikeSystem Design Case Study: Building a Scalable E-Commerce Platform - Hiike
System Design Case Study: Building a Scalable E-Commerce Platform - Hiike
Hiike
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Malak Abu Hammad
 
Deep Dive: Getting Funded with Jason Jason Lemkin Founder & CEO @ SaaStr
Deep Dive: Getting Funded with Jason Jason Lemkin Founder & CEO @ SaaStrDeep Dive: Getting Funded with Jason Jason Lemkin Founder & CEO @ SaaStr
Deep Dive: Getting Funded with Jason Jason Lemkin Founder & CEO @ SaaStr
saastr
 
Azure API Management to expose backend services securely
Azure API Management to expose backend services securelyAzure API Management to expose backend services securely
Azure API Management to expose backend services securely
Dinusha Kumarasiri
 
dbms calicut university B. sc Cs 4th sem.pdf
dbms  calicut university B. sc Cs 4th sem.pdfdbms  calicut university B. sc Cs 4th sem.pdf
dbms calicut university B. sc Cs 4th sem.pdf
Shinana2
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
Jason Packer
 
Trusted Execution Environment for Decentralized Process Mining
Trusted Execution Environment for Decentralized Process MiningTrusted Execution Environment for Decentralized Process Mining
Trusted Execution Environment for Decentralized Process Mining
LucaBarbaro3
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
tolgahangng
 
Operating System Used by Users in day-to-day life.pptx
Operating System Used by Users in day-to-day life.pptxOperating System Used by Users in day-to-day life.pptx
Operating System Used by Users in day-to-day life.pptx
Pravash Chandra Das
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
ssuserfac0301
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
akankshawande
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
Zilliz
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Tosin Akinosho
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
Jakub Marek
 
Letter and Document Automation for Bonterra Impact Management (fka Social Sol...
Letter and Document Automation for Bonterra Impact Management (fka Social Sol...Letter and Document Automation for Bonterra Impact Management (fka Social Sol...
Letter and Document Automation for Bonterra Impact Management (fka Social Sol...
Jeffrey Haguewood
 
Finale of the Year: Apply for Next One!
Finale of the Year: Apply for Next One!Finale of the Year: Apply for Next One!
Finale of the Year: Apply for Next One!
GDSC PJATK
 
AWS Cloud Cost Optimization Presentation.pptx
AWS Cloud Cost Optimization Presentation.pptxAWS Cloud Cost Optimization Presentation.pptx
AWS Cloud Cost Optimization Presentation.pptx
HarisZaheer8
 

Recently uploaded (20)

Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 
System Design Case Study: Building a Scalable E-Commerce Platform - Hiike
System Design Case Study: Building a Scalable E-Commerce Platform - HiikeSystem Design Case Study: Building a Scalable E-Commerce Platform - Hiike
System Design Case Study: Building a Scalable E-Commerce Platform - Hiike
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
 
Deep Dive: Getting Funded with Jason Jason Lemkin Founder & CEO @ SaaStr
Deep Dive: Getting Funded with Jason Jason Lemkin Founder & CEO @ SaaStrDeep Dive: Getting Funded with Jason Jason Lemkin Founder & CEO @ SaaStr
Deep Dive: Getting Funded with Jason Jason Lemkin Founder & CEO @ SaaStr
 
Azure API Management to expose backend services securely
Azure API Management to expose backend services securelyAzure API Management to expose backend services securely
Azure API Management to expose backend services securely
 
dbms calicut university B. sc Cs 4th sem.pdf
dbms  calicut university B. sc Cs 4th sem.pdfdbms  calicut university B. sc Cs 4th sem.pdf
dbms calicut university B. sc Cs 4th sem.pdf
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
 
Trusted Execution Environment for Decentralized Process Mining
Trusted Execution Environment for Decentralized Process MiningTrusted Execution Environment for Decentralized Process Mining
Trusted Execution Environment for Decentralized Process Mining
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
 
Operating System Used by Users in day-to-day life.pptx
Operating System Used by Users in day-to-day life.pptxOperating System Used by Users in day-to-day life.pptx
Operating System Used by Users in day-to-day life.pptx
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
 
Letter and Document Automation for Bonterra Impact Management (fka Social Sol...
Letter and Document Automation for Bonterra Impact Management (fka Social Sol...Letter and Document Automation for Bonterra Impact Management (fka Social Sol...
Letter and Document Automation for Bonterra Impact Management (fka Social Sol...
 
Finale of the Year: Apply for Next One!
Finale of the Year: Apply for Next One!Finale of the Year: Apply for Next One!
Finale of the Year: Apply for Next One!
 
AWS Cloud Cost Optimization Presentation.pptx
AWS Cloud Cost Optimization Presentation.pptxAWS Cloud Cost Optimization Presentation.pptx
AWS Cloud Cost Optimization Presentation.pptx
 

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