SlideShare a Scribd company logo
Inheritance
Prepared by
Dr.K.Vijayalakshmi & Mrs.N.Nithya
Department of Computer science and Engineering
Ramco Institute of Technology
Rajapalayam
CS8392- UNIT II INHERITANCE AND INTERFACES 9
• Inheritance – Super classes- sub classes –Protected
members – constructors in sub classes- the Object
class – abstract classes and methods- final methods
and classes – Interfaces – defining an interface,
implementing interface, differences between classes
and interfaces and extending interfaces - Object
cloning -inner classes, Array Lists - Strings
Contents
• Inheritance
• Super class and sub class
• Extends and protected keyword
• Types of inheritance
• Single inheritance
• Method overloading and method overriding
• Super keyword and its use
• Subclass constructor
• Object class
Concept of Inheritance
Source: NPTEL video – Programming in Java
Inheritance
• Inheritance can be defined as the procedure or mechanism of
acquiring all the properties and behaviour of one class to
another.
• Process of deriving a new class from the existing class is called
inheritance. New class is called sub class and Existing class is
called super class.
• It is the act of mechanism through which the object of one
class can acquire(inherit) the methods and data members of
another class.
Super class & Sub class
• Super Class:
• The class whose features are inherited is known as super
class(or a base class or a parent class).
• Sub Class:
• The class that inherits the other class is known as sub
class(or a derived class, extended class, or child class).
• A sub class is a specialized version of the super class.
• The subclass can add its own fields and methods in
addition to the superclass fields and methods.
Example:
Vehicle
Car Truck
Example:
• 2Dpoint and 3Dpoint
2Dpoint – superclass and 3Dpoint – subclass
• Person and Student
Person – superclass and Student – subclass
• Person and Employee
Person – superclass and Student – subclass
Example of Inheritance
• Superclass Fields : x, y
• Subclass Fields : x & y (Inherited), z
2DPoint
3DPoint
Reusability
• Inheritance supports the concept of “reusability”, i.e.
• When we want to create a new class, which is more specific
to a class that is already existing, we can derive our new
class from the existing class.
• By doing this, we are reusing the fields and methods of the
existing class.
Syntax - extends keyword
class SubClassName extends SuperClassName
{
//fields and methods
}
The meaning of extends is to increase the functionality.
Eg. Class student extends person
{
}
protected keyword
• A class’s private members are accessible only within the class
itself.
• A superclass’s protected members can be accessed
• by members of that superclass,
• by members of its subclasses and
• by members of other classes in the same package
Types of Inheritance
• Single inheritance - One sub
class is derived from one
super class
• multilevel inheritance - A
sub class is derived from
another sub class which is
derived from a super class.
• hierarchical inheritance-
Two or more sub classes
have the same super class
• Person – Student
• Animal – Dog
Student – Exam – Result
Person – Student
Person – Employee
https://nptel.ac.in/courses/106105191/13
Person
Student
Student
Exam
Result
Person
Student Employee
Purpose of inheritance
• Inheritance is the process by which objects of one class
acquire the properties and methods of another class.
• It provides the idea of reusability.
• We can add additional features to an existing class without
modifying it by deriving a new class from it- Extendibility
• Save development time
Single inheritance
• Deriving a single sub class from a single super class is called
single inheritance. It is derived using the keyword ‘extends’
class A
{ }
class B extends A
{ }
• class A is the super class from which the class B is derived.
• Class B inherits all the public and protected members of class
A but class B cannot access private members of class A.
Example for Single Inheritance
Circle
Sphere
• Example Programs
Output
Explanation
• Superclass Circle has a method display()
• Subclass Sphere has a method with the same name display()
• When calling display() with the subclass object, subclass’s display()
method is invoked.
Method Overloading
• Methods in a class having the same method name with
different number and type of arguments is said to be
method overloading.
• Method overloading is done at compile time.
• Number of parameter can be different.
• Types of parameter can be different.
Method Overriding
• The methods in the super class and its sub classes have the
same method name with same type and the same number
of arguments (same signature), this is referred as method
overriding.
• Method in sub classes overrides the method in super class.
• Eg. display() method in class Circle & class Sphere.
Class Poll
Class Poll
In which java oops feature one object can acquire all
the properties and behaviours of the parent object?
• Encapsulation
• Inheritance
• Polymorphism
• None of the above
Class Poll
What is subclass in java?
A subclass is a class that extends another class
A subclass is a class declared inside a class
Both above.
None of the above.
Class Poll
If class B is subclassed from class A then which is the
correct syntax
• class B:A{}
• class B extends A{}
• class B extends class A{}
• class B implements A{}
Super Keyword
1. To access the data members of immediate super
class when both super and sub class have member
with same name.
2. To access the method of immediate super class
when both super and sub class have methods with
same name.
3. To explicitly call the no-argument(default) and
parameterized constructor of super class
1. To access the data members of immediate
super class – both super and sub class should
have same member variable name
class Animal
{
String color="white";
}
class Dog extends Animal
{
String color="black";
void printColor()
{
System.out.println(color); //prints color of Dog class
System.out.println(super.color); //prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
} }
• In the above example, Animal and Dog both classes have a common
property color. If we print color property, it will print the color of
current class by default. To access the parent property, we need to
use super keyword as super.color
2. To access methods of immediate super
class – both super class and subclass should
have same method name and method
signature (Overridden method).
/* Base class Person */
class Person
{
void message()
{
System.out.println("This is person class");
}
}
/* Subclass Student */
class Student extends Person
{
void message()
{
System.out.println("This is student class");
}
// Note that display() is only in Student
class
void display()
{
message();
super.message();
}
}
/* Driver program to test */
class Test
{
public static void main(String args[])
{
Student s = new Student();
// calling display() of Student
s.display();
}
}
3. To explicitly call the no-argument(default)
and parameterized constructor of super class
Constructors in sub classes
subclass constructor
• Constructor which is defined in the subclass is called as
subclass constructor.
• Used to call the superclass constructor and construct the
instance variables of both superclass and subclass.
• Subclass constructor uses the keyword super() to invoke the
superclass constructor
• On object creation of sub class, first super class constructor
and then sub class constructor will be called.
Constructors in sub classes
super() can call both
• default as well as
• parameterized constructors
depending upon the situation.
Points to Remember
• Call to super() must be first statement in subclass constructor.
• If a constructor does not explicitly invoke a superclass constructor, the
Java compiler automatically inserts a call to the no-argument(default)
constructor of the superclass.
Class Poll
Order of execution of constructors in Java Inheritance is
• Base to derived class
• Derived to base class
• Random order
• none
Class Poll
Inheritance relationship in Java language is
• Association
• Is-A
• Has-A
• None
Class Poll
Advantage of inheritance in java programming is/are
• Code Re-usability
• Class Extendibility
• Save development time
• All
The object class
• Object class is present in java.lang package.
• Every class in Java is directly or indirectly derived from
the Object class.
• If a Class does not extend any other class, then it is direct
child class of Object and if extends other class then it is an
indirectly derived. Therefore the Object class methods are
available to all Java classes.
• Hence Object class acts as a root of inheritance hierarchy in
any Java Program.
Method Description
public final Class getClass() returns the Class class object of this object. The Class class can further be used to
get the metadata of this class.
public int hashCode() returns the hashcode number for this object.
public boolean equals(Object obj) compares the given object to this object.
protected Object clone() throws
CloneNotSupportedException
creates and returns the exact copy (clone) of this object.
public String toString() returns the string representation of this object.
public final void notify() wakes up single thread, waiting on this object's monitor.
public final void notifyAll() wakes up all the threads, waiting on this object's monitor.
public final void wait(long timeout)throws
InterruptedException
causes the current thread to wait for the specified milliseconds, until another
thread notifies (invokes notify() or notifyAll() method).
public final void wait(long timeout,int
nanos)throws InterruptedException
causes the current thread to wait for the specified milliseconds and nanoseconds,
until another thread notifies (invokes notify() or notifyAll() method).
public final void wait()throws
InterruptedException
causes the current thread to wait, until another thread notifies (invokes notify() or
notifyAll() method).
protected void finalize()throws Throwable is invoked by the garbage collector before object is being garbage collected.
How does these methods work?
• https://www.geeksforgeeks.org/object-class-in-java/
• Object class documentation Java SE 7
• https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html
• Object class Tutorial
• https://docs.oracle.com/javase/tutorial/java/IandI/objectclass.html
Method overloading Method overriding
• Methods in a class having the same
method name with different number
and type of arguments (different
signature) is said to be method
overloading.
• Method overloading is done at
compile time. Thus Compile Time
Polymorphism is achieved.
• Number of parameter can be
different.
• Types of parameter can be different.
• The methods in the super class and
its sub classes have the same method
name with same type and the same
number of arguments (same
signature), this is referred as method
overriding.
• Method overriding is one of the way
by which java achieve Run Time
Polymorphism.
• Number of parameters are same.
• Types of parameter are same.

More Related Content

What's hot

inheritance
inheritanceinheritance
inheritance
Nivetha Elangovan
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
Nilesh Dalvi
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
Vineeta Garg
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
Shubham Dwivedi
 
OOPS Basics With Example
OOPS Basics With ExampleOOPS Basics With Example
OOPS Basics With Example
Thooyavan Venkatachalam
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
Paumil Patel
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
Tech_MX
 
Java constructors
Java constructorsJava constructors
Java constructors
QUONTRASOLUTIONS
 
Constructor overloading & method overloading
Constructor overloading & method overloadingConstructor overloading & method overloading
Constructor overloading & method overloading
garishma bhatia
 
Inheritance in Java
Inheritance in JavaInheritance in Java
Inheritance in Java
Tamanna Akter
 
inheritance c++
inheritance c++inheritance c++
inheritance c++
Muraleedhar Sundararajan
 
Ppt on this and super keyword
Ppt on this and super keywordPpt on this and super keyword
Ppt on this and super keyword
tanu_jaswal
 
Java Data Types
Java Data TypesJava Data Types
Java Data Types
Spotle.ai
 
Unary operator overloading
Unary operator overloadingUnary operator overloading
Unary operator overloading
Md. Ashraful Islam
 
Inheritance in C++
Inheritance in C++Inheritance in C++
Inheritance in C++
Laxman Puri
 
Constructor and Types of Constructors
Constructor and Types of ConstructorsConstructor and Types of Constructors
Constructor and Types of Constructors
Dhrumil Panchal
 
Inheritance In Java
Inheritance In JavaInheritance In Java
Inheritance In Java
Arnab Bhaumik
 
Java keywords
Java keywordsJava keywords
Java keywords
Ravi_Kant_Sahu
 
Data types in java
Data types in javaData types in java
Data types in java
HarshitaAshwani
 
C++ Inheritance Tutorial | Introduction To Inheritance In C++ Programming Wit...
C++ Inheritance Tutorial | Introduction To Inheritance In C++ Programming Wit...C++ Inheritance Tutorial | Introduction To Inheritance In C++ Programming Wit...
C++ Inheritance Tutorial | Introduction To Inheritance In C++ Programming Wit...
Simplilearn
 

What's hot (20)

inheritance
inheritanceinheritance
inheritance
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
 
OOPS Basics With Example
OOPS Basics With ExampleOOPS Basics With Example
OOPS Basics With Example
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Java constructors
Java constructorsJava constructors
Java constructors
 
Constructor overloading & method overloading
Constructor overloading & method overloadingConstructor overloading & method overloading
Constructor overloading & method overloading
 
Inheritance in Java
Inheritance in JavaInheritance in Java
Inheritance in Java
 
inheritance c++
inheritance c++inheritance c++
inheritance c++
 
Ppt on this and super keyword
Ppt on this and super keywordPpt on this and super keyword
Ppt on this and super keyword
 
Java Data Types
Java Data TypesJava Data Types
Java Data Types
 
Unary operator overloading
Unary operator overloadingUnary operator overloading
Unary operator overloading
 
Inheritance in C++
Inheritance in C++Inheritance in C++
Inheritance in C++
 
Constructor and Types of Constructors
Constructor and Types of ConstructorsConstructor and Types of Constructors
Constructor and Types of Constructors
 
Inheritance In Java
Inheritance In JavaInheritance In Java
Inheritance In Java
 
Java keywords
Java keywordsJava keywords
Java keywords
 
Data types in java
Data types in javaData types in java
Data types in java
 
C++ Inheritance Tutorial | Introduction To Inheritance In C++ Programming Wit...
C++ Inheritance Tutorial | Introduction To Inheritance In C++ Programming Wit...C++ Inheritance Tutorial | Introduction To Inheritance In C++ Programming Wit...
C++ Inheritance Tutorial | Introduction To Inheritance In C++ Programming Wit...
 

Similar to Java Inheritance - sub class constructors - Method overriding

Ch5 inheritance
Ch5 inheritanceCh5 inheritance
Ch5 inheritance
HarshithaAllu
 
Unit3 inheritance
Unit3 inheritanceUnit3 inheritance
Unit3 inheritance
Kalai Selvi
 
L7 inheritance
L7 inheritanceL7 inheritance
L7 inheritance
teach4uin
 
L7 inheritance
L7 inheritanceL7 inheritance
L7 inheritance
teach4uin
 
PPT Lecture-1.4.pptx
PPT Lecture-1.4.pptxPPT Lecture-1.4.pptx
PPT Lecture-1.4.pptx
HimanshuPandey957216
 
Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1
PRN USM
 
Java chapter 5
Java chapter 5Java chapter 5
Java chapter 5
Abdii Rashid
 
Inheritance
InheritanceInheritance
Inheritance
Munsif Ullah
 
Unit3 part2-inheritance
Unit3 part2-inheritanceUnit3 part2-inheritance
Unit3 part2-inheritance
DevaKumari Vijay
 
Inheritance
Inheritance Inheritance
Inheritance
sourav verma
 
Java Inheritance
Java InheritanceJava Inheritance
Java Inheritance
Rosie Jane Enomar
 
Pi j3.1 inheritance
Pi j3.1 inheritancePi j3.1 inheritance
Pi j3.1 inheritance
mcollison
 
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
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
Lovely Professional University
 
Java - Inheritance Concepts
Java - Inheritance ConceptsJava - Inheritance Concepts
Java - Inheritance Concepts
Victer Paul
 
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
 
inheritance.pptx
inheritance.pptxinheritance.pptx
inheritance.pptx
sonukumarjha12
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
Dr.Neeraj Kumar Pandey
 
UNIT - IIInew.pptx
UNIT - IIInew.pptxUNIT - IIInew.pptx
UNIT - IIInew.pptx
akila m
 
البرمجة الهدفية بلغة جافا - الوراثة
البرمجة الهدفية بلغة جافا - الوراثةالبرمجة الهدفية بلغة جافا - الوراثة
البرمجة الهدفية بلغة جافا - الوراثة
Mahmoud Alfarra
 

Similar to Java Inheritance - sub class constructors - Method overriding (20)

Ch5 inheritance
Ch5 inheritanceCh5 inheritance
Ch5 inheritance
 
Unit3 inheritance
Unit3 inheritanceUnit3 inheritance
Unit3 inheritance
 
L7 inheritance
L7 inheritanceL7 inheritance
L7 inheritance
 
L7 inheritance
L7 inheritanceL7 inheritance
L7 inheritance
 
PPT Lecture-1.4.pptx
PPT Lecture-1.4.pptxPPT Lecture-1.4.pptx
PPT Lecture-1.4.pptx
 
Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1
 
Java chapter 5
Java chapter 5Java chapter 5
Java chapter 5
 
Inheritance
InheritanceInheritance
Inheritance
 
Unit3 part2-inheritance
Unit3 part2-inheritanceUnit3 part2-inheritance
Unit3 part2-inheritance
 
Inheritance
Inheritance Inheritance
Inheritance
 
Java Inheritance
Java InheritanceJava Inheritance
Java Inheritance
 
Pi j3.1 inheritance
Pi j3.1 inheritancePi j3.1 inheritance
Pi j3.1 inheritance
 
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
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Java - Inheritance Concepts
Java - Inheritance ConceptsJava - Inheritance Concepts
Java - Inheritance Concepts
 
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
 
inheritance.pptx
inheritance.pptxinheritance.pptx
inheritance.pptx
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
 
UNIT - IIInew.pptx
UNIT - IIInew.pptxUNIT - IIInew.pptx
UNIT - IIInew.pptx
 
البرمجة الهدفية بلغة جافا - الوراثة
البرمجة الهدفية بلغة جافا - الوراثةالبرمجة الهدفية بلغة جافا - الوراثة
البرمجة الهدفية بلغة جافا - الوراثة
 

Recently uploaded

Unbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptxUnbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptx
ChristineTorrepenida1
 
Self-Control of Emotions by Slidesgo.pptx
Self-Control of Emotions by Slidesgo.pptxSelf-Control of Emotions by Slidesgo.pptx
Self-Control of Emotions by Slidesgo.pptx
iemerc2024
 
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdfTutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
aqil azizi
 
Hierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power SystemHierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power System
Kerry Sado
 
A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...
nooriasukmaningtyas
 
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
insn4465
 
PPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testingPPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testing
anoopmanoharan2
 
digital fundamental by Thomas L.floydl.pdf
digital fundamental by Thomas L.floydl.pdfdigital fundamental by Thomas L.floydl.pdf
digital fundamental by Thomas L.floydl.pdf
drwaing
 
DfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributionsDfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributions
gestioneergodomus
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
thanhdowork
 
New techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdfNew techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdf
wisnuprabawa3
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
obonagu
 
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdfBPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
MIGUELANGEL966976
 
原版制作(unimelb毕业证书)墨尔本大学毕业证Offer一模一样
原版制作(unimelb毕业证书)墨尔本大学毕业证Offer一模一样原版制作(unimelb毕业证书)墨尔本大学毕业证Offer一模一样
原版制作(unimelb毕业证书)墨尔本大学毕业证Offer一模一样
obonagu
 
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECTCHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
jpsjournal1
 
sieving analysis and results interpretation
sieving analysis and results interpretationsieving analysis and results interpretation
sieving analysis and results interpretation
ssuser36d3051
 
ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...
ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...
ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...
Mukeshwaran Balu
 
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
ihlasbinance2003
 
[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
awadeshbabu
 
spirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptxspirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptx
Madan Karki
 

Recently uploaded (20)

Unbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptxUnbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptx
 
Self-Control of Emotions by Slidesgo.pptx
Self-Control of Emotions by Slidesgo.pptxSelf-Control of Emotions by Slidesgo.pptx
Self-Control of Emotions by Slidesgo.pptx
 
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdfTutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
 
Hierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power SystemHierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power System
 
A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...
 
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
 
PPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testingPPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testing
 
digital fundamental by Thomas L.floydl.pdf
digital fundamental by Thomas L.floydl.pdfdigital fundamental by Thomas L.floydl.pdf
digital fundamental by Thomas L.floydl.pdf
 
DfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributionsDfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributions
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
 
New techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdfNew techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdf
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
 
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdfBPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
 
原版制作(unimelb毕业证书)墨尔本大学毕业证Offer一模一样
原版制作(unimelb毕业证书)墨尔本大学毕业证Offer一模一样原版制作(unimelb毕业证书)墨尔本大学毕业证Offer一模一样
原版制作(unimelb毕业证书)墨尔本大学毕业证Offer一模一样
 
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECTCHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
 
sieving analysis and results interpretation
sieving analysis and results interpretationsieving analysis and results interpretation
sieving analysis and results interpretation
 
ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...
ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...
ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...
 
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
 
[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
 
spirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptxspirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptx
 

Java Inheritance - sub class constructors - Method overriding

  • 1. Inheritance Prepared by Dr.K.Vijayalakshmi & Mrs.N.Nithya Department of Computer science and Engineering Ramco Institute of Technology Rajapalayam
  • 2. CS8392- UNIT II INHERITANCE AND INTERFACES 9 • Inheritance – Super classes- sub classes –Protected members – constructors in sub classes- the Object class – abstract classes and methods- final methods and classes – Interfaces – defining an interface, implementing interface, differences between classes and interfaces and extending interfaces - Object cloning -inner classes, Array Lists - Strings
  • 3. Contents • Inheritance • Super class and sub class • Extends and protected keyword • Types of inheritance • Single inheritance • Method overloading and method overriding • Super keyword and its use • Subclass constructor • Object class
  • 4. Concept of Inheritance Source: NPTEL video – Programming in Java
  • 5. Inheritance • Inheritance can be defined as the procedure or mechanism of acquiring all the properties and behaviour of one class to another. • Process of deriving a new class from the existing class is called inheritance. New class is called sub class and Existing class is called super class. • It is the act of mechanism through which the object of one class can acquire(inherit) the methods and data members of another class.
  • 6. Super class & Sub class • Super Class: • The class whose features are inherited is known as super class(or a base class or a parent class). • Sub Class: • The class that inherits the other class is known as sub class(or a derived class, extended class, or child class). • A sub class is a specialized version of the super class. • The subclass can add its own fields and methods in addition to the superclass fields and methods.
  • 8. Example: • 2Dpoint and 3Dpoint 2Dpoint – superclass and 3Dpoint – subclass • Person and Student Person – superclass and Student – subclass • Person and Employee Person – superclass and Student – subclass
  • 9. Example of Inheritance • Superclass Fields : x, y • Subclass Fields : x & y (Inherited), z 2DPoint 3DPoint
  • 10. Reusability • Inheritance supports the concept of “reusability”, i.e. • When we want to create a new class, which is more specific to a class that is already existing, we can derive our new class from the existing class. • By doing this, we are reusing the fields and methods of the existing class.
  • 11. Syntax - extends keyword class SubClassName extends SuperClassName { //fields and methods } The meaning of extends is to increase the functionality. Eg. Class student extends person { }
  • 12. protected keyword • A class’s private members are accessible only within the class itself. • A superclass’s protected members can be accessed • by members of that superclass, • by members of its subclasses and • by members of other classes in the same package
  • 13. Types of Inheritance • Single inheritance - One sub class is derived from one super class • multilevel inheritance - A sub class is derived from another sub class which is derived from a super class. • hierarchical inheritance- Two or more sub classes have the same super class • Person – Student • Animal – Dog Student – Exam – Result Person – Student Person – Employee https://nptel.ac.in/courses/106105191/13 Person Student Student Exam Result Person Student Employee
  • 14. Purpose of inheritance • Inheritance is the process by which objects of one class acquire the properties and methods of another class. • It provides the idea of reusability. • We can add additional features to an existing class without modifying it by deriving a new class from it- Extendibility • Save development time
  • 15. Single inheritance • Deriving a single sub class from a single super class is called single inheritance. It is derived using the keyword ‘extends’ class A { } class B extends A { } • class A is the super class from which the class B is derived. • Class B inherits all the public and protected members of class A but class B cannot access private members of class A.
  • 16. Example for Single Inheritance Circle Sphere
  • 18. Output Explanation • Superclass Circle has a method display() • Subclass Sphere has a method with the same name display() • When calling display() with the subclass object, subclass’s display() method is invoked.
  • 19. Method Overloading • Methods in a class having the same method name with different number and type of arguments is said to be method overloading. • Method overloading is done at compile time. • Number of parameter can be different. • Types of parameter can be different.
  • 20. Method Overriding • The methods in the super class and its sub classes have the same method name with same type and the same number of arguments (same signature), this is referred as method overriding. • Method in sub classes overrides the method in super class. • Eg. display() method in class Circle & class Sphere.
  • 22. Class Poll In which java oops feature one object can acquire all the properties and behaviours of the parent object? • Encapsulation • Inheritance • Polymorphism • None of the above
  • 23. Class Poll What is subclass in java? A subclass is a class that extends another class A subclass is a class declared inside a class Both above. None of the above.
  • 24. Class Poll If class B is subclassed from class A then which is the correct syntax • class B:A{} • class B extends A{} • class B extends class A{} • class B implements A{}
  • 25. Super Keyword 1. To access the data members of immediate super class when both super and sub class have member with same name. 2. To access the method of immediate super class when both super and sub class have methods with same name. 3. To explicitly call the no-argument(default) and parameterized constructor of super class
  • 26. 1. To access the data members of immediate super class – both super and sub class should have same member variable name
  • 27. class Animal { String color="white"; } class Dog extends Animal { String color="black"; void printColor() { System.out.println(color); //prints color of Dog class System.out.println(super.color); //prints color of Animal class } } class TestSuper1{ public static void main(String args[]){ Dog d=new Dog(); d.printColor(); } }
  • 28. • In the above example, Animal and Dog both classes have a common property color. If we print color property, it will print the color of current class by default. To access the parent property, we need to use super keyword as super.color
  • 29. 2. To access methods of immediate super class – both super class and subclass should have same method name and method signature (Overridden method).
  • 30. /* Base class Person */ class Person { void message() { System.out.println("This is person class"); } } /* Subclass Student */ class Student extends Person { void message() { System.out.println("This is student class"); } // Note that display() is only in Student class void display() { message(); super.message(); } }
  • 31. /* Driver program to test */ class Test { public static void main(String args[]) { Student s = new Student(); // calling display() of Student s.display(); } }
  • 32. 3. To explicitly call the no-argument(default) and parameterized constructor of super class
  • 34. subclass constructor • Constructor which is defined in the subclass is called as subclass constructor. • Used to call the superclass constructor and construct the instance variables of both superclass and subclass. • Subclass constructor uses the keyword super() to invoke the superclass constructor • On object creation of sub class, first super class constructor and then sub class constructor will be called.
  • 35. Constructors in sub classes super() can call both • default as well as • parameterized constructors depending upon the situation.
  • 36.
  • 37.
  • 38. Points to Remember • Call to super() must be first statement in subclass constructor. • If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument(default) constructor of the superclass.
  • 39. Class Poll Order of execution of constructors in Java Inheritance is • Base to derived class • Derived to base class • Random order • none
  • 40. Class Poll Inheritance relationship in Java language is • Association • Is-A • Has-A • None
  • 41. Class Poll Advantage of inheritance in java programming is/are • Code Re-usability • Class Extendibility • Save development time • All
  • 42. The object class • Object class is present in java.lang package. • Every class in Java is directly or indirectly derived from the Object class. • If a Class does not extend any other class, then it is direct child class of Object and if extends other class then it is an indirectly derived. Therefore the Object class methods are available to all Java classes. • Hence Object class acts as a root of inheritance hierarchy in any Java Program.
  • 43. Method Description public final Class getClass() returns the Class class object of this object. The Class class can further be used to get the metadata of this class. public int hashCode() returns the hashcode number for this object. public boolean equals(Object obj) compares the given object to this object. protected Object clone() throws CloneNotSupportedException creates and returns the exact copy (clone) of this object. public String toString() returns the string representation of this object. public final void notify() wakes up single thread, waiting on this object's monitor. public final void notifyAll() wakes up all the threads, waiting on this object's monitor. public final void wait(long timeout)throws InterruptedException causes the current thread to wait for the specified milliseconds, until another thread notifies (invokes notify() or notifyAll() method). public final void wait(long timeout,int nanos)throws InterruptedException causes the current thread to wait for the specified milliseconds and nanoseconds, until another thread notifies (invokes notify() or notifyAll() method). public final void wait()throws InterruptedException causes the current thread to wait, until another thread notifies (invokes notify() or notifyAll() method). protected void finalize()throws Throwable is invoked by the garbage collector before object is being garbage collected.
  • 44. How does these methods work? • https://www.geeksforgeeks.org/object-class-in-java/ • Object class documentation Java SE 7 • https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html • Object class Tutorial • https://docs.oracle.com/javase/tutorial/java/IandI/objectclass.html
  • 45. Method overloading Method overriding • Methods in a class having the same method name with different number and type of arguments (different signature) is said to be method overloading. • Method overloading is done at compile time. Thus Compile Time Polymorphism is achieved. • Number of parameter can be different. • Types of parameter can be different. • The methods in the super class and its sub classes have the same method name with same type and the same number of arguments (same signature), this is referred as method overriding. • Method overriding is one of the way by which java achieve Run Time Polymorphism. • Number of parameters are same. • Types of parameter are same.