SlideShare une entreprise Scribd logo
1  sur  45
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.

Contenu connexe

Tendances

Tendances (20)

Constructor overloading & method overloading
Constructor overloading & method overloadingConstructor overloading & method overloading
Constructor overloading & method overloading
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
 
Abstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core JavaAbstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core Java
 
Java(Polymorphism)
Java(Polymorphism)Java(Polymorphism)
Java(Polymorphism)
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Abstract class in java
Abstract class in javaAbstract class in java
Abstract class in java
 
Unit 9. Structure and Unions
Unit 9. Structure and UnionsUnit 9. Structure and Unions
Unit 9. Structure and Unions
 
Inheritance In Java
Inheritance In JavaInheritance In Java
Inheritance In Java
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
class and objects
class and objectsclass and objects
class and objects
 
Structures in c++
Structures in c++Structures in c++
Structures in c++
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
 
friend function(c++)
friend function(c++)friend function(c++)
friend function(c++)
 
Java basics and java variables
Java basics and java variablesJava basics and java variables
Java basics and java variables
 
Method overloading
Method overloadingMethod overloading
Method overloading
 
Polymorphism presentation in java
Polymorphism presentation in javaPolymorphism presentation in java
Polymorphism presentation in java
 
Constructors in java
Constructors in javaConstructors in java
Constructors in java
 
Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
 
Java package
Java packageJava package
Java package
 

Similaire à Java Inheritance - sub class constructors - Method overriding

Unit3 inheritance
Unit3 inheritanceUnit3 inheritance
Unit3 inheritanceKalai Selvi
 
L7 inheritance
L7 inheritanceL7 inheritance
L7 inheritanceteach4uin
 
L7 inheritance
L7 inheritanceL7 inheritance
L7 inheritanceteach4uin
 
Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1PRN USM
 
Pi j3.1 inheritance
Pi j3.1 inheritancePi j3.1 inheritance
Pi j3.1 inheritancemcollison
 
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 examplesSunil Kumar Gunasekaran
 
Java - Inheritance Concepts
Java - Inheritance ConceptsJava - Inheritance Concepts
Java - Inheritance ConceptsVicter 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.pptAshwathGupta
 
UNIT - IIInew.pptx
UNIT - IIInew.pptxUNIT - IIInew.pptx
UNIT - IIInew.pptxakila m
 
البرمجة الهدفية بلغة جافا - الوراثة
البرمجة الهدفية بلغة جافا - الوراثةالبرمجة الهدفية بلغة جافا - الوراثة
البرمجة الهدفية بلغة جافا - الوراثةMahmoud Alfarra
 
9781439035665 ppt ch10
9781439035665 ppt ch109781439035665 ppt ch10
9781439035665 ppt ch10Terry Yoast
 

Similaire à 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
 
UNIT - IIInew.pptx
UNIT - IIInew.pptxUNIT - IIInew.pptx
UNIT - IIInew.pptx
 
البرمجة الهدفية بلغة جافا - الوراثة
البرمجة الهدفية بلغة جافا - الوراثةالبرمجة الهدفية بلغة جافا - الوراثة
البرمجة الهدفية بلغة جافا - الوراثة
 
9781439035665 ppt ch10
9781439035665 ppt ch109781439035665 ppt ch10
9781439035665 ppt ch10
 

Dernier

Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx959SahilShah
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...asadnawaz62
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxKartikeyaDwivedi3
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptSAURABHKUMAR892774
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEroselinkalist12
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
Solving The Right Triangles PowerPoint 2.ppt
Solving The Right Triangles PowerPoint 2.pptSolving The Right Triangles PowerPoint 2.ppt
Solving The Right Triangles PowerPoint 2.pptJasonTagapanGulla
 
Earthing details of Electrical Substation
Earthing details of Electrical SubstationEarthing details of Electrical Substation
Earthing details of Electrical Substationstephanwindworld
 
Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...121011101441
 
lifi-technology with integration of IOT.pptx
lifi-technology with integration of IOT.pptxlifi-technology with integration of IOT.pptx
lifi-technology with integration of IOT.pptxsomshekarkn64
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)Dr SOUNDIRARAJ N
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxk795866
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsyncWhy does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsyncssuser2ae721
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfAsst.prof M.Gokilavani
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfme23b1001
 

Dernier (20)

Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptx
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.ppt
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
Solving The Right Triangles PowerPoint 2.ppt
Solving The Right Triangles PowerPoint 2.pptSolving The Right Triangles PowerPoint 2.ppt
Solving The Right Triangles PowerPoint 2.ppt
 
Earthing details of Electrical Substation
Earthing details of Electrical SubstationEarthing details of Electrical Substation
Earthing details of Electrical Substation
 
Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...
 
lifi-technology with integration of IOT.pptx
lifi-technology with integration of IOT.pptxlifi-technology with integration of IOT.pptx
lifi-technology with integration of IOT.pptx
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptx
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsyncWhy does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdf
 
young call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Serviceyoung call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Service
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.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.