SlideShare a Scribd company logo
1
InheritanceInheritance
2
Agenda
● What is and Why Inheritance?
● How to derive a sub-class?
● Object class
● Constructor calling chain
● “super” keyword
● Overriding methods
● Hiding methods
● Hiding fields
● Type casting
● Final class and final methods
3
What isWhat is
Inheritance?Inheritance?
4
What is Inheritance?
● Inheritance is the concept of a child class (sub class)
automatically inheriting the variables and methods
defined in its parent class (super class).
● A primary feature of object-oriented programming
along with encapsulation and polymorphism
5
Why Inheritance? Reusability
● Benefits of Inheritance in OOP : Reusability
– Once a behavior (method) is defined in a super class,
that behavior is automatically inherited by all subclasses
● Thus, you write a method only once and it can be used by
all subclasses.
– Once a set of properties (fields) are defined in a super
class, the same set of properties are inherited by all
subclasses
● A class and its children share common set of properties
– A subclass only needs to implement the differences
between itself and the parent.
6
How to derive aHow to derive a
sub-class?sub-class?
7
extends keyword
● To derive a child class, we use the extends keyword.
● Suppose we have a parent class called Person.
public class Person {
protected String name;
protected String address;
/**
* Default constructor
*/
public Person(){
System.out.println(“Inside Person:Constructor”);
name = ""; address = "";
}
. . . .
}
8
extends keyword
● Now, we want to create another class named Student
● Since a student is also a person, we decide to just
extend the class Person, so that we can inherit all the
properties and methods of the existing class Person.
● To do this, we write,
public class Student extends Person {
public Student(){
System.out.println(“Inside Student:Constructor”);
}
. . . .
}
9
What You Can Do in a Sub-class
● A subclass inherits all of the “public” and “protected”
members (fields or methods) of its parent, no matter
what package the subclass is in
● If the subclass is in the same package as its parent,
it also inherits the package-private members (fields
or methods) of the parent
10
What You Can Do in a Sub-class
Regarding Fields
● The inherited fields can be used directly, just like any
other fields.
● You can declare new fields in the subclass that are
not in the super class
● You can declare a field in the subclass with the same
name as the one in the super class, thus hiding it
(not recommended).
● A subclass does not inherit the private members of
its parent class. However, if the super class has
public or protected methods for accessing its private
fields, these can also be used by the subclass.
11
What You Can Do in a Sub-class
Regarding Methods
● The inherited methods can be used directly as they are.
● You can write a new instance method in the subclass that
has the same signature as the one in the super class,
thus overriding it.
● You can write a new static method in the subclass that
has the same signature as the one in the super class,
thus hiding it.
● You can declare new methods in the subclass that are
not in the super class.
12
Object ClassObject Class
13
Object Class
● Object class is mother of all classes
– In Java language, all classes are sub-classed (extended)
from the Object super class
– Object class is the only class that does not have a parent
class
● Defines and implements behavior common to all
classes including the ones that you write
– getClass()
– equals()
– toString()
– ...
14
Class Hierarchy
● A sample class hierarchy
15
Super class & Sub class
● Super class (Parent class)
– Any class above a specific class in the class hierarchy.
● Sub class (Child class)
– Any class below a specific class in the class hierarchy.
16
Constructor CallingConstructor Calling
ChainChain
17
How Constructor method of a Super
class gets called
● A subclass constructor invokes the constructor of
the super class implicitly
– When a Student object, a subclass (child class), is
instantiated, the default constructor of its super class
(parent class), Person class, is invoked implicitly before
sub-class's constructor method is invoked
● A subclass constructor can invoke the constructor
of the super explicitly by using the “super” keyword
– The constructor of the Student class can explicitly invoke
the constructor of the Person class using “super”
keyword
– Used when passing parameters to the constructor of the
super class
18
Example: Constructor Calling Chain
● To illustrate this, consider the following code,
● In the code, we create an object of class Student.
The output of the program is,
public static void main( String[] args ){
Student anna = new Student();
}
Inside Person:Constructor
Inside Student:Constructor
19
Example: Constructor Calling Chain
● The program flow is shown below.
20
““super” keywordsuper” keyword
21
The “super” keyword
● A subclass can also explicitly call a constructor of
its immediate super class.
● This is done by using the super constructor call.
● A super constructor call in the constructor of a
subclass will result in the execution of relevant
constructor from the super class, based on the
arguments passed.
22
The “super” keyword
● For example, given our previous example classes
Person and Student, we show an example of a
super constructor call.
● Given the following code for Student,
public Student(){
super( "SomeName", "SomeAddress" );
System.out.println("Inside Student:Constructor");
}
23
The “super” keyword
● Few things to remember when using the super
constructor call:
– The super() call must occur as the first statement in a
constructor
– The super() call can only be used in a constructor (not in
ordinary methods)
24
The “super” keyword
● Another use of super is to refer to members of the
super class (just like the this reference ).
● For example,
public Student() {
super.name = “somename”;
super.address = “some address”;
}
25
Overriding MethodsOverriding Methods
26
Overriding methods
● If a derived class needs to have a different
implementation of a certain instance method from
that of the super class, override that instance
method in the sub class
– Note that the scheme of overriding applies only to
instance methods
– For static methods, it is called hiding methods
● The overriding method has the same name,
number and type of parameters, and return type as
the method it overrides
● The overriding method can also return a subtype of
the type returned by the overridden method. This is
called a covariant return type
27
Example: Overriding Methods
● Suppose we have the following implementation for
the getName method in the Person super class,
public class Person {
:
:
public String getName(){
System.out.println("Parent: getName");
return name;
}
}
28
Example: Overriding Methods
● To override the getName method of the super class
Person in the subclass Student, reimplement the
method with the same signature
● Now, when we invoke the getName method of an
object of the subclass Student, the getName method of
the Student would be called, and the output would be,
public class Student extends Person{
:
public String getName(){
System.out.println("Student: getName");
return name;
}
:
}
Student: getName
29
Modifiers in the Overriding Methods
● The access specifier for an overriding method can
allow more, but not less, access than the overridden
method
– For example, a protected instance method in the super
class can be made public, but not private, in the subclass.
● You will get a compile-time error if you attempt to
change an instance method in the super class to a
class method in the subclass, and vice versa
30
RuntimeRuntime
Polymorphism withPolymorphism with
Overriding MethodsOverriding Methods
31
What is Polymorphism?
● Polymorphism in a Java program
– The ability of a reference variable to change
behavior according to what object instance it is
holding.
– This allows multiple objects of different subclasses
to be treated as objects of a single super class,
while automatically selecting the proper methods to
apply to a particular object based on the subclass it
belongs to
– (We will talk more on Polymorphism during our
Polymorphism presentation.)
32
Example: Runtime Polymorphism
Code:
Person person2 = new Student();
person2.myMethod("test4");
Person person3 = new InternationalStudent();
person3.myMethod("test5");
Result:
myMethod(test4) in Student class is called
myMethod(test5) in InternationalStudent class is called
33
Hiding MethodsHiding Methods
34
Hiding Methods
● If a subclass defines a class method (static method)
with the same signature as a class method in the
super class, the method in the subclass “hides” the
one in the super class
35
Example: Coding of Hiding Static
Method
class Animal {
public static void testClassMethod() {
System.out.println("The class method in Animal.");
}
}
// The testClassMethod() of the child class hides the one of the
// super class – it looks like overriding, doesn't it? But
// there is difference. We will talk about in the following slide.
class Cat extends Animal {
public static void testClassMethod() {
System.out.println("The class method in Cat.");
}
}
36
Overriding Method vs. Hiding Method
● Hiding a static method of a super class looks like
overriding an instance method of a super class
● The difference comes during runtime
– When you override an instance method, you get the benefit
of run-time polymorphism
– When you override an static method, there is no runt-time
polymorphism
37
Example: Overriding Method vs. Hiding
Method during Runtime
// Create object instance of Cat.
Cat myCat = new Cat();
// The object instance is Cat type
// and assigned to Animal type variable.
Animal myAnimal2 = myCat;
// For static method, the static method of
// the super class gets called.
Animal.testClassMethod();
// For instance method, the instance method
// of the subclass is called even though
// myAnimal2 is a super class type. This is
// run-time polymorphism.
myAnimal2.testInstanceMethod();
38
Hiding FieldsHiding Fields
39
Hiding Fields
● Within a sub class, a field that has the same name as
a field in the super class hides the super class' field,
even if their types are different
● Within the subclass, the field in the super class
cannot be referenced by its simple name
– Instead, the field must be accessed through super keyword
● Generally speaking, hiding fields is not a
recommended programming practice as it makes
code difficult to read
40
Type CastingType Casting
41
What is “Type”?
● When an object instance is created from a class, we
say the object instance is “type” of the class and its
super classes
● Example:
Student student1 = new Student();
– student1 object instance is the type of Student or it is
Student type
– student1 object instance is also type of Person if Student is
a child class of Person
– student1 object instance is also type of Object
42
What is Significance?
● An object instance of a particular type can be used in
any place where an instance of the type and its super
type is called for
● Example:
– student1 object instance is a “type” of TuftsStudent,
Student, and Peson
– student1 object can be used in any place where object
instance of the type of TuftsStudent, Student, or Person is
called for
● This enables polymorphism
43
Implicit Type Casting
● An object instance of a subclass can be assigned to a
variable (reference) of a parent class through implicit
type casting – this is safe since an object instance of a
subclass “is” also the type of the super class
● Example
– Let's assume Student class is a child class of Person class
– Let's assume TuftsStudent class is a child class of Student
class
TuftsStudent tuftstudent = new TuftsStudent();
Student student = tuftsstudent; // Implicit type casting
Person person = tuftsstudent; // Implicit type casting
Object object = tuftsstudent; // Implicit type casting
44
Type Casting between Objects
tuftsstudent
student
person
TuftsStudent
Object instance
45
Explicit Type Casting
● An object instance of a super class must be assigned to
a variable (reference) of a child class through explicit
type casting
– Not doing it will result in a compile error since the type
assignment is not safe
– Compiler wants to make sure you know what you are doing
● Example
– Let's assume Student class is a child class of Person class
Person person1 = new Student();
Student student1 = (Student) person1; // Explicit type casting
46
Runtime Type Mismatch Exception
● Even with explicit casting, you could still end up
having a runtime error
● Example
– Let's assume Student class is a child class of Person class
– Let's assume Teacher class is also a child class of Person
class
Person person1 = new Student();
Person person2 = new Teacher();
Student student1 = (Student) person1; // Explicit type casting
// No compile error, but runtime type mismatch exception
Student student2 = (Student) person2;
47
Use instanceof Operator to
Prevent Runtime Type Mismatch Error
● You can check the type of the object instance using
instanceof before the type casting
● Example
Person person1 = new Student();
Person person2 = new Teacher();
// Do the casting only when the type is verified
if (person2 instanceof Student) {
Student student2 = (Student) person2;
}
48
Final Class &Final Class &
Final MethodFinal Method
49
Final Classes
● Final Classes
– Classes that cannot be extended
– To declare final classes, we write,
public final ClassName{
. . .
}
● Example:
● Other examples of final classes are your wrapper
classes and String class
– You cannot create a subclass of String class
public final class Person {
. . .
}
50
Final Methods
● Final Methods
– Methods that cannot be overridden
– To declare final methods, we write,
public final [returnType] [methodName]([parameters]){
. . .
}
●
Static methods are automatically final
51
Example: final Methods
public final String getName(){
return name;
}
52
InheritanceInheritance
Ad

More Related Content

What's hot (20)

Inheritance
InheritanceInheritance
Inheritance
Sapna Sharma
 
Interface
InterfaceInterface
Interface
kamal kotecha
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
Raja Sekhar
 
Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPT
Pooja Jaiswal
 
Java access modifiers
Java access modifiersJava access modifiers
Java access modifiers
Srinivas Reddy
 
Java: Inheritance
Java: InheritanceJava: Inheritance
Java: Inheritance
Tareq Hasan
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
Lovely Professional University
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
SURIT DATTA
 
Object oriented programming With C#
Object oriented programming With C#Object oriented programming With C#
Object oriented programming With C#
Youssef Mohammed Abohaty
 
Object-oriented Programming-with C#
Object-oriented Programming-with C#Object-oriented Programming-with C#
Object-oriented Programming-with C#
Doncho Minkov
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
Sony India Software Center
 
Inheritance In Java
Inheritance In JavaInheritance In Java
Inheritance In Java
Darpan Chelani
 
Virtual base class
Virtual base classVirtual base class
Virtual base class
Tech_MX
 
Java Presentation For Syntax
Java Presentation For SyntaxJava Presentation For Syntax
Java Presentation For Syntax
PravinYalameli
 
Java package
Java packageJava package
Java package
CS_GDRCST
 
6. static keyword
6. static keyword6. static keyword
6. static keyword
Indu Sharma Bhardwaj
 
Inheritance in oops
Inheritance in oopsInheritance in oops
Inheritance in oops
Hirra Sultan
 
Control statements in java
Control statements in javaControl statements in java
Control statements in java
Madishetty Prathibha
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
Shubham Dwivedi
 
Object Oriented Programming with C#
Object Oriented Programming with C#Object Oriented Programming with C#
Object Oriented Programming with C#
foreverredpb
 

Viewers also liked (15)

Java inheritance
Java inheritanceJava inheritance
Java inheritance
Arati Gadgil
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
Tech_MX
 
Inheritance
InheritanceInheritance
Inheritance
Selvin Josy Bai Somu
 
Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...
Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...
Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...
cprogrammings
 
Inheritance in C++
Inheritance in C++Inheritance in C++
Inheritance in C++
Laxman Puri
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
BHUVIJAYAVELU
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
Vineeta Garg
 
C++ Inheritance
C++ InheritanceC++ Inheritance
C++ Inheritance
Jussi Pohjolainen
 
inheritance c++
inheritance c++inheritance c++
inheritance c++
Muraleedhar Sundararajan
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
COMSATS Institute of Information Technology
 
Java Classes methods and inheritance
Java Classes methods and inheritanceJava Classes methods and inheritance
Java Classes methods and inheritance
Srinivas Reddy
 
Jamon 22
Jamon 22Jamon 22
Jamon 22
Syed Shahul
 
Inheritance chepter 7
Inheritance chepter 7Inheritance chepter 7
Inheritance chepter 7
kamal kotecha
 
Inheritance in C++
Inheritance in C++Inheritance in C++
Inheritance in C++
Digvijay Singh Karakoti
 
Computer Hardware Basics (Components to be understand)
Computer Hardware Basics (Components to be understand)Computer Hardware Basics (Components to be understand)
Computer Hardware Basics (Components to be understand)
Digvijay Singh Karakoti
 
Ad

Similar to Java Inheritance (20)

javainheritance
javainheritancejavainheritance
javainheritance
Arjun Shanka
 
Java Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overridingJava Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overriding
NithyaN19
 
Modules 333333333³3444444444444444444.pptx
Modules 333333333³3444444444444444444.pptxModules 333333333³3444444444444444444.pptx
Modules 333333333³3444444444444444444.pptx
radhikacordise
 
04inherit
04inherit04inherit
04inherit
Waheed Warraich
 
Unit3 inheritance
Unit3 inheritanceUnit3 inheritance
Unit3 inheritance
Kalai Selvi
 
Unit3 part2-inheritance
Unit3 part2-inheritanceUnit3 part2-inheritance
Unit3 part2-inheritance
DevaKumari Vijay
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
Hamid Ghorbani
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examples
Sunil Kumar Gunasekaran
 
البرمجة الهدفية بلغة جافا - الوراثة
البرمجة الهدفية بلغة جافا - الوراثةالبرمجة الهدفية بلغة جافا - الوراثة
البرمجة الهدفية بلغة جافا - الوراثة
Mahmoud Alfarra
 
06 InheritanceAndPolymorphism.ppt
06 InheritanceAndPolymorphism.ppt06 InheritanceAndPolymorphism.ppt
06 InheritanceAndPolymorphism.ppt
ParikhitGhosh1
 
InheritanceAndPolymorphismprein Java.ppt
InheritanceAndPolymorphismprein Java.pptInheritanceAndPolymorphismprein Java.ppt
InheritanceAndPolymorphismprein Java.ppt
gayatridwahane
 
702641313-CS3391-OBJORIENTEDPS-Unit-2.pptx
702641313-CS3391-OBJORIENTEDPS-Unit-2.pptx702641313-CS3391-OBJORIENTEDPS-Unit-2.pptx
702641313-CS3391-OBJORIENTEDPS-Unit-2.pptx
SAJITHABANUS
 
Ch5 inheritance
Ch5 inheritanceCh5 inheritance
Ch5 inheritance
HarshithaAllu
 
Core java oop
Core java oopCore java oop
Core java oop
Parth Shah
 
Chapter 05 polymorphism extra
Chapter 05 polymorphism extraChapter 05 polymorphism extra
Chapter 05 polymorphism extra
Nurhanna Aziz
 
INHERITANCE IN JAVA.pptx
INHERITANCE IN JAVA.pptxINHERITANCE IN JAVA.pptx
INHERITANCE IN JAVA.pptx
NITHISG1
 
Java chapter 5
Java chapter 5Java chapter 5
Java chapter 5
Abdii Rashid
 
Only oop
Only oopOnly oop
Only oop
anitarooge
 
Inheritance and Polymorphism
Inheritance and PolymorphismInheritance and Polymorphism
Inheritance and Polymorphism
KartikKapgate
 
Python_Unit_3.pdf
Python_Unit_3.pdfPython_Unit_3.pdf
Python_Unit_3.pdf
alaparthi
 
Java Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overridingJava Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overriding
NithyaN19
 
Modules 333333333³3444444444444444444.pptx
Modules 333333333³3444444444444444444.pptxModules 333333333³3444444444444444444.pptx
Modules 333333333³3444444444444444444.pptx
radhikacordise
 
Unit3 inheritance
Unit3 inheritanceUnit3 inheritance
Unit3 inheritance
Kalai Selvi
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examples
Sunil Kumar Gunasekaran
 
البرمجة الهدفية بلغة جافا - الوراثة
البرمجة الهدفية بلغة جافا - الوراثةالبرمجة الهدفية بلغة جافا - الوراثة
البرمجة الهدفية بلغة جافا - الوراثة
Mahmoud Alfarra
 
06 InheritanceAndPolymorphism.ppt
06 InheritanceAndPolymorphism.ppt06 InheritanceAndPolymorphism.ppt
06 InheritanceAndPolymorphism.ppt
ParikhitGhosh1
 
InheritanceAndPolymorphismprein Java.ppt
InheritanceAndPolymorphismprein Java.pptInheritanceAndPolymorphismprein Java.ppt
InheritanceAndPolymorphismprein Java.ppt
gayatridwahane
 
702641313-CS3391-OBJORIENTEDPS-Unit-2.pptx
702641313-CS3391-OBJORIENTEDPS-Unit-2.pptx702641313-CS3391-OBJORIENTEDPS-Unit-2.pptx
702641313-CS3391-OBJORIENTEDPS-Unit-2.pptx
SAJITHABANUS
 
Chapter 05 polymorphism extra
Chapter 05 polymorphism extraChapter 05 polymorphism extra
Chapter 05 polymorphism extra
Nurhanna Aziz
 
INHERITANCE IN JAVA.pptx
INHERITANCE IN JAVA.pptxINHERITANCE IN JAVA.pptx
INHERITANCE IN JAVA.pptx
NITHISG1
 
Inheritance and Polymorphism
Inheritance and PolymorphismInheritance and Polymorphism
Inheritance and Polymorphism
KartikKapgate
 
Python_Unit_3.pdf
Python_Unit_3.pdfPython_Unit_3.pdf
Python_Unit_3.pdf
alaparthi
 
Ad

More from Rosie Jane Enomar (7)

IEEE 802 standards
IEEE 802 standardsIEEE 802 standards
IEEE 802 standards
Rosie Jane Enomar
 
Chapter 6 - Networking
Chapter 6 - NetworkingChapter 6 - Networking
Chapter 6 - Networking
Rosie Jane Enomar
 
Software development
Software developmentSoftware development
Software development
Rosie Jane Enomar
 
Special operators in Database
Special operators in DatabaseSpecial operators in Database
Special operators in Database
Rosie Jane Enomar
 
Aggregate functions
Aggregate functionsAggregate functions
Aggregate functions
Rosie Jane Enomar
 
Juncture
JunctureJuncture
Juncture
Rosie Jane Enomar
 
Types of Reaction
Types of ReactionTypes of Reaction
Types of Reaction
Rosie Jane Enomar
 

Recently uploaded (20)

Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
larencebapu132
 
SPRING FESTIVITIES - UK AND USA -
SPRING FESTIVITIES - UK AND USA            -SPRING FESTIVITIES - UK AND USA            -
SPRING FESTIVITIES - UK AND USA -
Colégio Santa Teresinha
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
Operations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdfOperations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdf
Arab Academy for Science, Technology and Maritime Transport
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptxSCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
Ronisha Das
 
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Celine George
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
Social Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy StudentsSocial Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy Students
DrNidhiAgarwal
 
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Library Association of Ireland
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
New Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptxNew Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptx
milanasargsyan5
 
Quality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdfQuality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdf
Dr. Bindiya Chauhan
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
larencebapu132
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptxSCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
Ronisha Das
 
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Celine George
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
Social Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy StudentsSocial Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy Students
DrNidhiAgarwal
 
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Library Association of Ireland
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
New Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptxNew Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptx
milanasargsyan5
 
Quality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdfQuality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdf
Dr. Bindiya Chauhan
 

Java Inheritance

  • 2. 2 Agenda ● What is and Why Inheritance? ● How to derive a sub-class? ● Object class ● Constructor calling chain ● “super” keyword ● Overriding methods ● Hiding methods ● Hiding fields ● Type casting ● Final class and final methods
  • 4. 4 What is Inheritance? ● Inheritance is the concept of a child class (sub class) automatically inheriting the variables and methods defined in its parent class (super class). ● A primary feature of object-oriented programming along with encapsulation and polymorphism
  • 5. 5 Why Inheritance? Reusability ● Benefits of Inheritance in OOP : Reusability – Once a behavior (method) is defined in a super class, that behavior is automatically inherited by all subclasses ● Thus, you write a method only once and it can be used by all subclasses. – Once a set of properties (fields) are defined in a super class, the same set of properties are inherited by all subclasses ● A class and its children share common set of properties – A subclass only needs to implement the differences between itself and the parent.
  • 6. 6 How to derive aHow to derive a sub-class?sub-class?
  • 7. 7 extends keyword ● To derive a child class, we use the extends keyword. ● Suppose we have a parent class called Person. public class Person { protected String name; protected String address; /** * Default constructor */ public Person(){ System.out.println(“Inside Person:Constructor”); name = ""; address = ""; } . . . . }
  • 8. 8 extends keyword ● Now, we want to create another class named Student ● Since a student is also a person, we decide to just extend the class Person, so that we can inherit all the properties and methods of the existing class Person. ● To do this, we write, public class Student extends Person { public Student(){ System.out.println(“Inside Student:Constructor”); } . . . . }
  • 9. 9 What You Can Do in a Sub-class ● A subclass inherits all of the “public” and “protected” members (fields or methods) of its parent, no matter what package the subclass is in ● If the subclass is in the same package as its parent, it also inherits the package-private members (fields or methods) of the parent
  • 10. 10 What You Can Do in a Sub-class Regarding Fields ● The inherited fields can be used directly, just like any other fields. ● You can declare new fields in the subclass that are not in the super class ● You can declare a field in the subclass with the same name as the one in the super class, thus hiding it (not recommended). ● A subclass does not inherit the private members of its parent class. However, if the super class has public or protected methods for accessing its private fields, these can also be used by the subclass.
  • 11. 11 What You Can Do in a Sub-class Regarding Methods ● The inherited methods can be used directly as they are. ● You can write a new instance method in the subclass that has the same signature as the one in the super class, thus overriding it. ● You can write a new static method in the subclass that has the same signature as the one in the super class, thus hiding it. ● You can declare new methods in the subclass that are not in the super class.
  • 13. 13 Object Class ● Object class is mother of all classes – In Java language, all classes are sub-classed (extended) from the Object super class – Object class is the only class that does not have a parent class ● Defines and implements behavior common to all classes including the ones that you write – getClass() – equals() – toString() – ...
  • 14. 14 Class Hierarchy ● A sample class hierarchy
  • 15. 15 Super class & Sub class ● Super class (Parent class) – Any class above a specific class in the class hierarchy. ● Sub class (Child class) – Any class below a specific class in the class hierarchy.
  • 17. 17 How Constructor method of a Super class gets called ● A subclass constructor invokes the constructor of the super class implicitly – When a Student object, a subclass (child class), is instantiated, the default constructor of its super class (parent class), Person class, is invoked implicitly before sub-class's constructor method is invoked ● A subclass constructor can invoke the constructor of the super explicitly by using the “super” keyword – The constructor of the Student class can explicitly invoke the constructor of the Person class using “super” keyword – Used when passing parameters to the constructor of the super class
  • 18. 18 Example: Constructor Calling Chain ● To illustrate this, consider the following code, ● In the code, we create an object of class Student. The output of the program is, public static void main( String[] args ){ Student anna = new Student(); } Inside Person:Constructor Inside Student:Constructor
  • 19. 19 Example: Constructor Calling Chain ● The program flow is shown below.
  • 21. 21 The “super” keyword ● A subclass can also explicitly call a constructor of its immediate super class. ● This is done by using the super constructor call. ● A super constructor call in the constructor of a subclass will result in the execution of relevant constructor from the super class, based on the arguments passed.
  • 22. 22 The “super” keyword ● For example, given our previous example classes Person and Student, we show an example of a super constructor call. ● Given the following code for Student, public Student(){ super( "SomeName", "SomeAddress" ); System.out.println("Inside Student:Constructor"); }
  • 23. 23 The “super” keyword ● Few things to remember when using the super constructor call: – The super() call must occur as the first statement in a constructor – The super() call can only be used in a constructor (not in ordinary methods)
  • 24. 24 The “super” keyword ● Another use of super is to refer to members of the super class (just like the this reference ). ● For example, public Student() { super.name = “somename”; super.address = “some address”; }
  • 26. 26 Overriding methods ● If a derived class needs to have a different implementation of a certain instance method from that of the super class, override that instance method in the sub class – Note that the scheme of overriding applies only to instance methods – For static methods, it is called hiding methods ● The overriding method has the same name, number and type of parameters, and return type as the method it overrides ● The overriding method can also return a subtype of the type returned by the overridden method. This is called a covariant return type
  • 27. 27 Example: Overriding Methods ● Suppose we have the following implementation for the getName method in the Person super class, public class Person { : : public String getName(){ System.out.println("Parent: getName"); return name; } }
  • 28. 28 Example: Overriding Methods ● To override the getName method of the super class Person in the subclass Student, reimplement the method with the same signature ● Now, when we invoke the getName method of an object of the subclass Student, the getName method of the Student would be called, and the output would be, public class Student extends Person{ : public String getName(){ System.out.println("Student: getName"); return name; } : } Student: getName
  • 29. 29 Modifiers in the Overriding Methods ● The access specifier for an overriding method can allow more, but not less, access than the overridden method – For example, a protected instance method in the super class can be made public, but not private, in the subclass. ● You will get a compile-time error if you attempt to change an instance method in the super class to a class method in the subclass, and vice versa
  • 31. 31 What is Polymorphism? ● Polymorphism in a Java program – The ability of a reference variable to change behavior according to what object instance it is holding. – This allows multiple objects of different subclasses to be treated as objects of a single super class, while automatically selecting the proper methods to apply to a particular object based on the subclass it belongs to – (We will talk more on Polymorphism during our Polymorphism presentation.)
  • 32. 32 Example: Runtime Polymorphism Code: Person person2 = new Student(); person2.myMethod("test4"); Person person3 = new InternationalStudent(); person3.myMethod("test5"); Result: myMethod(test4) in Student class is called myMethod(test5) in InternationalStudent class is called
  • 34. 34 Hiding Methods ● If a subclass defines a class method (static method) with the same signature as a class method in the super class, the method in the subclass “hides” the one in the super class
  • 35. 35 Example: Coding of Hiding Static Method class Animal { public static void testClassMethod() { System.out.println("The class method in Animal."); } } // The testClassMethod() of the child class hides the one of the // super class – it looks like overriding, doesn't it? But // there is difference. We will talk about in the following slide. class Cat extends Animal { public static void testClassMethod() { System.out.println("The class method in Cat."); } }
  • 36. 36 Overriding Method vs. Hiding Method ● Hiding a static method of a super class looks like overriding an instance method of a super class ● The difference comes during runtime – When you override an instance method, you get the benefit of run-time polymorphism – When you override an static method, there is no runt-time polymorphism
  • 37. 37 Example: Overriding Method vs. Hiding Method during Runtime // Create object instance of Cat. Cat myCat = new Cat(); // The object instance is Cat type // and assigned to Animal type variable. Animal myAnimal2 = myCat; // For static method, the static method of // the super class gets called. Animal.testClassMethod(); // For instance method, the instance method // of the subclass is called even though // myAnimal2 is a super class type. This is // run-time polymorphism. myAnimal2.testInstanceMethod();
  • 39. 39 Hiding Fields ● Within a sub class, a field that has the same name as a field in the super class hides the super class' field, even if their types are different ● Within the subclass, the field in the super class cannot be referenced by its simple name – Instead, the field must be accessed through super keyword ● Generally speaking, hiding fields is not a recommended programming practice as it makes code difficult to read
  • 41. 41 What is “Type”? ● When an object instance is created from a class, we say the object instance is “type” of the class and its super classes ● Example: Student student1 = new Student(); – student1 object instance is the type of Student or it is Student type – student1 object instance is also type of Person if Student is a child class of Person – student1 object instance is also type of Object
  • 42. 42 What is Significance? ● An object instance of a particular type can be used in any place where an instance of the type and its super type is called for ● Example: – student1 object instance is a “type” of TuftsStudent, Student, and Peson – student1 object can be used in any place where object instance of the type of TuftsStudent, Student, or Person is called for ● This enables polymorphism
  • 43. 43 Implicit Type Casting ● An object instance of a subclass can be assigned to a variable (reference) of a parent class through implicit type casting – this is safe since an object instance of a subclass “is” also the type of the super class ● Example – Let's assume Student class is a child class of Person class – Let's assume TuftsStudent class is a child class of Student class TuftsStudent tuftstudent = new TuftsStudent(); Student student = tuftsstudent; // Implicit type casting Person person = tuftsstudent; // Implicit type casting Object object = tuftsstudent; // Implicit type casting
  • 44. 44 Type Casting between Objects tuftsstudent student person TuftsStudent Object instance
  • 45. 45 Explicit Type Casting ● An object instance of a super class must be assigned to a variable (reference) of a child class through explicit type casting – Not doing it will result in a compile error since the type assignment is not safe – Compiler wants to make sure you know what you are doing ● Example – Let's assume Student class is a child class of Person class Person person1 = new Student(); Student student1 = (Student) person1; // Explicit type casting
  • 46. 46 Runtime Type Mismatch Exception ● Even with explicit casting, you could still end up having a runtime error ● Example – Let's assume Student class is a child class of Person class – Let's assume Teacher class is also a child class of Person class Person person1 = new Student(); Person person2 = new Teacher(); Student student1 = (Student) person1; // Explicit type casting // No compile error, but runtime type mismatch exception Student student2 = (Student) person2;
  • 47. 47 Use instanceof Operator to Prevent Runtime Type Mismatch Error ● You can check the type of the object instance using instanceof before the type casting ● Example Person person1 = new Student(); Person person2 = new Teacher(); // Do the casting only when the type is verified if (person2 instanceof Student) { Student student2 = (Student) person2; }
  • 48. 48 Final Class &Final Class & Final MethodFinal Method
  • 49. 49 Final Classes ● Final Classes – Classes that cannot be extended – To declare final classes, we write, public final ClassName{ . . . } ● Example: ● Other examples of final classes are your wrapper classes and String class – You cannot create a subclass of String class public final class Person { . . . }
  • 50. 50 Final Methods ● Final Methods – Methods that cannot be overridden – To declare final methods, we write, public final [returnType] [methodName]([parameters]){ . . . } ● Static methods are automatically final
  • 51. 51 Example: final Methods public final String getName(){ return name; }