SlideShare a Scribd company logo
1
Inheritance
Classes and Subclasses
Or Extending a Class
2
Inheritance: Introduction
 Reusability--building new components by
utilising existing components- is yet another
important aspect of OO paradigm.
 It is always good/“productive” if we are able to
reuse something that is already exists rather
than creating the same all over again.
 This is achieve by creating new classes, reusing
the properties of existing classes.
3
Inheritance: Introduction
 This mechanism of
deriving a new class
from existing/old class is
called “inheritance”.
 The old class is known as
“base” class, “super”
class or “parent” class”;
and the new class is
known as “sub” class,
“derived” class, or “child”
class.
Parent
Child
Inherited
capability
4
Inheritance: Introduction
 The inheritance allows subclasses to inherit all
properties (variables and methods) of their
parent classes. The different forms of
inheritance are:
 Single inheritance (only one super class)
 Multiple inheritance (several super classes)
 Hierarchical inheritance (one super class, many sub
classes)
 Multi-Level inheritance (derived from a derived
class)
 Hybrid inheritance (more than two types)
 Multi-path inheritance (inheritance of some
properties from two sources).
5
Forms of Inheritance
A
B
(a) Single Inheritance
A
C
(b) Multiple Inheritance
B A
C
(c) Hierarchical Inheritance
B D
A
C
(a) Multi-Level Inheritance
B
B
D
(b) Hybrid Inheritance
c
A
B
D
(b) Multipath Inheritance
c
A
6
Defining a Sub class
 A subclass/child class is defined as follows:
 The keyword “extends” signifies that the properties of
super class are extended to the subclass. That means,
subclass contains its own members as well of those of
the super class. This kind of situation occurs when we
want to enhance properties of existing class without
actually modifying it.
class SubClassName extends SuperClassName
{
fields declaration;
methods declaration;
}
7
Subclasses and Inheritance
 Circle class captures basic properties
 For drawing application, need a circle to
draw itself on the screen, GraphicCircle...
 This can be realised either by updating the
circle class itself (which is not a good
Software Engineering method) or creating a
new class that builds on the existing class
and add additional properties.
8
Without Inheritance
 Not very elegant
public class GraphicCircle {
public Circle c; // keep a copy of a circle
public double area() { return c.area(); }
public double circumference (){ return c.circumference(); }
// new instance variables, methods for this class
public Color outline, fill;
public void draw(DrawWindow dw) { /* drawing code here */ }
}
9
Subclasses and Inheritance
 Circle class captures basic properties
 For drawing application need a circle to
draw itself on the screen, GraphicCircle
 Java/OOP allows for Circle class code to be
implicitly (re)used in defining a GraphicCircle
 GraphicCircle becomes a subclass of Circle,
extending its capabilities
10
Circle
x,y,r : double
area ( ) : double
circumference(): double
GraphicCircle
outline, fill : Color
draw (DrawWindow ) : void
Superclass
base class,
Or parent
class
Subclass,
Derived
class, or
Child class
Subclassing Circle
11
Subclassing
 Subclasses created by the keyword
extends:
 Each GraphicCircle object is also a Circle!
public class GraphicCircle extends Circle {
// automatically inherit all the variables and methods
// of Circle, so only need to put in the ‘new stuff’
Color outline, fill;
public void draw(DrawWindow dw) {
dw.drawCircle(x,y,r,outline,fill);
}
}
12
Final Classes
 Declaring class with final modifier
prevents it being extended or subclassed.
 Allows compiler to optimize the invoking
of methods of the class
final class Cirlce{
…………
}
13
Subclasses & Constructors
 Default constructor automatically calls
constructor of the base class:
GraphicCircle drawableCircle = new GraphicCircle();
default constructor
for Circle class is
called
14
Subclasses & Constructors
 Defined constructor can invoke base class constructor
with super:
public GraphicCircle(double x, double y, double r,
Color outline, Color fill) {
super(x, y, r);
this.outline = outline;
this fill = fill
}
15
Shadowed Variables
 Subclasses defining variables with the
same name as those in the superclass,
shadow them:
16
Shadowed Variables - Example
public class Circle {
public float r = 100;
}
public class GraphicCircle extends Circle {
public float r = 10; // New variable, resolution in dots per inch
}
public class CircleTest {
public static void main(String[] args){
GraphicCircle gc = new GraphicCircle();
Circle c = gc;
System.out.println(“ GraphicCircleRadius= “ + gc.r); // 10
System.out.println (“ Circle Radius = “ + c.r); // 100
}
}
17
Overriding Methods
 Derived/sub classes defining methods
with same name, return type and
arguments as those in the parent/super
class, override their parents methods:
18
Overriding Methods
class A {
int j = 1;
int f( ) { return j; }
}
class B extends A {
int j = 2;
int f( ) {
return j; }
}
19
Overriding Methods
class override_test {
public static void main(String args[]) {
B b = new B();
System.out.println(b.j); // refers to B.j prints 2
System.out.println(b.f()); // refers to B.f prints 2
A a = (A) b;
System.out.println(a.j); // now refers to a.j prints 1
System.out.println(a.f()); // overridden method still refers to B.f() prints 2 !
}
}
Object Type Casting
[raj@mundroo] inheritance [1:167] java override_test
2
2
1
2
20
Using All in One: Person and Student
Person
name: String
sex: char
age: int
Display ( ) : void
Student
RollNo: int
Branch: String
Display() : void
Superclass
class
Subclass
class.
21
Person class: Parent class
// Student.java: Student inheriting properties of person class
class person
{
private String name;
protected char sex; // note protected
public int age;
person()
{
name = null;
sex = 'U'; // unknown
age = 0;
}
person(String name, char sex, int age)
{
this.name = name;
this.sex = sex;
this.age = age;
}
String getName()
{
return name;
}
void Display()
{
System.out.println("Name = "+name);
System.out.println("Sex = "+sex);
System.out.println("Age = "+age);
}
}
22
Student class: Derived class
class student extends person
{
private int RollNo;
String branch;
student(String name, char sex, int age, int RollNo, String branch)
{
super(name, sex, age); // calls parent class's constructor with 3 arguments
this.RollNo = RollNo;
this.branch = branch;
}
void Display() // Method Overriding
{
System.out.println("Roll No = "+RollNo);
System.out.println("Name = "+getName());
System.out.println("Sex = "+sex);
System.out.println("Age = "+age);
System.out.println("Branch = "+branch);
}
void TestMethod() // test what is valid to access
{
// name = "Mark"; Error: name is private
sex = 'M';
RollNo = 20;
}
}
What happens if super class constructor is not explicitly invoked ?
(default constructor will be invoked).
23
Driver Class
class MyTest
{
public static void main(String args[] )
{
student s1 = new student("Rama", 'M', 21, 1, "Computer Science");
student s2 = new student("Sita", 'F', 19, 2, "Software Engineering");
System.out.println("Student 1 Details...");
s1.Display();
System.out.println("Student 2 Details...");
s2.Display();
person p1 = new person("Rao", 'M', 45);
System.out.println("Person Details...");
p1.Display();
}
}
Can we create Object of person class ?
24
Output
[raj@mundroo] inheritance [1:154] java MyTest
Student 1 Details...
Roll No = 1
Name = Rama
Sex = M
Age = 21
Branch = Computer Science
Student 2 Details...
Roll No = 2
Name = Sita
Sex = F
Age = 19
Branch = Software Engineering
Person Details...
Name = Rao
Sex = M
Age = 45
[raj@mundroo] inheritance [1:155]
25
Summary
 Inheritance promotes reusability by supporting
the creation of new classes from existing
classes.
 Various forms of inheritance can be realised in
Java.
 Child class constructor can be directed to
invoke selected constructor from parent using
super keyword.
 Variables and Methods from parent classes can
be overridden by redefining them in derived
classes.
 New Keywords: extends, super, final
26
References
 Chapter 8: Sections 8.11, 8.12, 8.13, and
8.14 from Java book by Balagurusamy
 Optional: <for in depth>
 Chapter 14: Inheritance from “Mastering
C++” by Venugopal and Buyya!

More Related Content

PPTX
10. inheritance
M H Buddhika Ariyaratne
 
PPTX
Java Inheritance - sub class constructors - Method overriding
NithyaN19
 
PPTX
Inheritance Slides
Ahsan Raja
 
PDF
Unit 2
Amar Jukuntla
 
PPTX
Ch5 inheritance
HarshithaAllu
 
PPT
Chapter 8 Inheritance
OUM SAOKOSAL
 
PDF
Java programming -Object-Oriented Thinking- Inheritance
Jyothishmathi Institute of Technology and Science Karimnagar
 
10. inheritance
M H Buddhika Ariyaratne
 
Java Inheritance - sub class constructors - Method overriding
NithyaN19
 
Inheritance Slides
Ahsan Raja
 
Ch5 inheritance
HarshithaAllu
 
Chapter 8 Inheritance
OUM SAOKOSAL
 
Java programming -Object-Oriented Thinking- Inheritance
Jyothishmathi Institute of Technology and Science Karimnagar
 

Similar to RajLec10.ppt (20)

PPT
Java Programming - Inheritance
Oum Saokosal
 
PPT
Inheritance & Polymorphism - 1
PRN USM
 
PPTX
Chapter 8.2
sotlsoc
 
PPT
M251_Meeting 5 (Inheritance and Polymorphism).ppt
smartashammari
 
PPT
Unit 7 inheritance
atcnerd
 
PPTX
‫Chapter3 inheritance
Mahmoud Alfarra
 
DOCX
Class notes(week 6) on inheritance and multiple inheritance
Kuntal Bhowmick
 
PDF
Java Inheritance
Rosie Jane Enomar
 
PPTX
20.2 Java inheritance
Intro C# Book
 
PPTX
UNIT 5.pptx
CurativeServiceDivis
 
PDF
Java OOP Programming language (Part 5) - Inheritance
OUM SAOKOSAL
 
PPT
Java inheritance
GaneshKumarKanthiah
 
PPTX
Chap-3 Inheritance.pptx
chetanpatilcp783
 
PPT
Chapter 5 (OOP Principles).ppt
henokmetaferia1
 
PPTX
Chap3 inheritance
raksharao
 
PPT
inheritance of java...basics of java in ppt
ssuserec53e73
 
PPTX
Unit3 part2-inheritance
DevaKumari Vijay
 
PPTX
Inheritance ppt
Nivegeetha
 
PPTX
Unit3 inheritance
Kalai Selvi
 
PPTX
OOPS_Unit2.inheritance and interface objected oriented programming
ssuserf45a65
 
Java Programming - Inheritance
Oum Saokosal
 
Inheritance & Polymorphism - 1
PRN USM
 
Chapter 8.2
sotlsoc
 
M251_Meeting 5 (Inheritance and Polymorphism).ppt
smartashammari
 
Unit 7 inheritance
atcnerd
 
‫Chapter3 inheritance
Mahmoud Alfarra
 
Class notes(week 6) on inheritance and multiple inheritance
Kuntal Bhowmick
 
Java Inheritance
Rosie Jane Enomar
 
20.2 Java inheritance
Intro C# Book
 
Java OOP Programming language (Part 5) - Inheritance
OUM SAOKOSAL
 
Java inheritance
GaneshKumarKanthiah
 
Chap-3 Inheritance.pptx
chetanpatilcp783
 
Chapter 5 (OOP Principles).ppt
henokmetaferia1
 
Chap3 inheritance
raksharao
 
inheritance of java...basics of java in ppt
ssuserec53e73
 
Unit3 part2-inheritance
DevaKumari Vijay
 
Inheritance ppt
Nivegeetha
 
Unit3 inheritance
Kalai Selvi
 
OOPS_Unit2.inheritance and interface objected oriented programming
ssuserf45a65
 
Ad

Recently uploaded (20)

PPTX
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
PPTX
IT Runs Better with ThousandEyes AI-driven Assurance
ThousandEyes
 
PDF
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
PPTX
Introduction to Flutter by Ayush Desai.pptx
ayushdesai204
 
PDF
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
PDF
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
PDF
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
PPTX
Agile Chennai 18-19 July 2025 | Emerging patterns in Agentic AI by Bharani Su...
AgileNetwork
 
PDF
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
PDF
The Future of Artificial Intelligence (AI)
Mukul
 
PDF
GDG Cloud Munich - Intro - Luiz Carneiro - #BuildWithAI - July - Abdel.pdf
Luiz Carneiro
 
PDF
Doc9.....................................
SofiaCollazos
 
PDF
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
PDF
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
PDF
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
PDF
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
PDF
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
PDF
How ETL Control Logic Keeps Your Pipelines Safe and Reliable.pdf
Stryv Solutions Pvt. Ltd.
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
Research-Fundamentals-and-Topic-Development.pdf
ayesha butalia
 
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
IT Runs Better with ThousandEyes AI-driven Assurance
ThousandEyes
 
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
Introduction to Flutter by Ayush Desai.pptx
ayushdesai204
 
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
Agile Chennai 18-19 July 2025 | Emerging patterns in Agentic AI by Bharani Su...
AgileNetwork
 
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
The Future of Artificial Intelligence (AI)
Mukul
 
GDG Cloud Munich - Intro - Luiz Carneiro - #BuildWithAI - July - Abdel.pdf
Luiz Carneiro
 
Doc9.....................................
SofiaCollazos
 
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
How ETL Control Logic Keeps Your Pipelines Safe and Reliable.pdf
Stryv Solutions Pvt. Ltd.
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Research-Fundamentals-and-Topic-Development.pdf
ayesha butalia
 
Ad

RajLec10.ppt

  • 2. 2 Inheritance: Introduction  Reusability--building new components by utilising existing components- is yet another important aspect of OO paradigm.  It is always good/“productive” if we are able to reuse something that is already exists rather than creating the same all over again.  This is achieve by creating new classes, reusing the properties of existing classes.
  • 3. 3 Inheritance: Introduction  This mechanism of deriving a new class from existing/old class is called “inheritance”.  The old class is known as “base” class, “super” class or “parent” class”; and the new class is known as “sub” class, “derived” class, or “child” class. Parent Child Inherited capability
  • 4. 4 Inheritance: Introduction  The inheritance allows subclasses to inherit all properties (variables and methods) of their parent classes. The different forms of inheritance are:  Single inheritance (only one super class)  Multiple inheritance (several super classes)  Hierarchical inheritance (one super class, many sub classes)  Multi-Level inheritance (derived from a derived class)  Hybrid inheritance (more than two types)  Multi-path inheritance (inheritance of some properties from two sources).
  • 5. 5 Forms of Inheritance A B (a) Single Inheritance A C (b) Multiple Inheritance B A C (c) Hierarchical Inheritance B D A C (a) Multi-Level Inheritance B B D (b) Hybrid Inheritance c A B D (b) Multipath Inheritance c A
  • 6. 6 Defining a Sub class  A subclass/child class is defined as follows:  The keyword “extends” signifies that the properties of super class are extended to the subclass. That means, subclass contains its own members as well of those of the super class. This kind of situation occurs when we want to enhance properties of existing class without actually modifying it. class SubClassName extends SuperClassName { fields declaration; methods declaration; }
  • 7. 7 Subclasses and Inheritance  Circle class captures basic properties  For drawing application, need a circle to draw itself on the screen, GraphicCircle...  This can be realised either by updating the circle class itself (which is not a good Software Engineering method) or creating a new class that builds on the existing class and add additional properties.
  • 8. 8 Without Inheritance  Not very elegant public class GraphicCircle { public Circle c; // keep a copy of a circle public double area() { return c.area(); } public double circumference (){ return c.circumference(); } // new instance variables, methods for this class public Color outline, fill; public void draw(DrawWindow dw) { /* drawing code here */ } }
  • 9. 9 Subclasses and Inheritance  Circle class captures basic properties  For drawing application need a circle to draw itself on the screen, GraphicCircle  Java/OOP allows for Circle class code to be implicitly (re)used in defining a GraphicCircle  GraphicCircle becomes a subclass of Circle, extending its capabilities
  • 10. 10 Circle x,y,r : double area ( ) : double circumference(): double GraphicCircle outline, fill : Color draw (DrawWindow ) : void Superclass base class, Or parent class Subclass, Derived class, or Child class Subclassing Circle
  • 11. 11 Subclassing  Subclasses created by the keyword extends:  Each GraphicCircle object is also a Circle! public class GraphicCircle extends Circle { // automatically inherit all the variables and methods // of Circle, so only need to put in the ‘new stuff’ Color outline, fill; public void draw(DrawWindow dw) { dw.drawCircle(x,y,r,outline,fill); } }
  • 12. 12 Final Classes  Declaring class with final modifier prevents it being extended or subclassed.  Allows compiler to optimize the invoking of methods of the class final class Cirlce{ ………… }
  • 13. 13 Subclasses & Constructors  Default constructor automatically calls constructor of the base class: GraphicCircle drawableCircle = new GraphicCircle(); default constructor for Circle class is called
  • 14. 14 Subclasses & Constructors  Defined constructor can invoke base class constructor with super: public GraphicCircle(double x, double y, double r, Color outline, Color fill) { super(x, y, r); this.outline = outline; this fill = fill }
  • 15. 15 Shadowed Variables  Subclasses defining variables with the same name as those in the superclass, shadow them:
  • 16. 16 Shadowed Variables - Example public class Circle { public float r = 100; } public class GraphicCircle extends Circle { public float r = 10; // New variable, resolution in dots per inch } public class CircleTest { public static void main(String[] args){ GraphicCircle gc = new GraphicCircle(); Circle c = gc; System.out.println(“ GraphicCircleRadius= “ + gc.r); // 10 System.out.println (“ Circle Radius = “ + c.r); // 100 } }
  • 17. 17 Overriding Methods  Derived/sub classes defining methods with same name, return type and arguments as those in the parent/super class, override their parents methods:
  • 18. 18 Overriding Methods class A { int j = 1; int f( ) { return j; } } class B extends A { int j = 2; int f( ) { return j; } }
  • 19. 19 Overriding Methods class override_test { public static void main(String args[]) { B b = new B(); System.out.println(b.j); // refers to B.j prints 2 System.out.println(b.f()); // refers to B.f prints 2 A a = (A) b; System.out.println(a.j); // now refers to a.j prints 1 System.out.println(a.f()); // overridden method still refers to B.f() prints 2 ! } } Object Type Casting [raj@mundroo] inheritance [1:167] java override_test 2 2 1 2
  • 20. 20 Using All in One: Person and Student Person name: String sex: char age: int Display ( ) : void Student RollNo: int Branch: String Display() : void Superclass class Subclass class.
  • 21. 21 Person class: Parent class // Student.java: Student inheriting properties of person class class person { private String name; protected char sex; // note protected public int age; person() { name = null; sex = 'U'; // unknown age = 0; } person(String name, char sex, int age) { this.name = name; this.sex = sex; this.age = age; } String getName() { return name; } void Display() { System.out.println("Name = "+name); System.out.println("Sex = "+sex); System.out.println("Age = "+age); } }
  • 22. 22 Student class: Derived class class student extends person { private int RollNo; String branch; student(String name, char sex, int age, int RollNo, String branch) { super(name, sex, age); // calls parent class's constructor with 3 arguments this.RollNo = RollNo; this.branch = branch; } void Display() // Method Overriding { System.out.println("Roll No = "+RollNo); System.out.println("Name = "+getName()); System.out.println("Sex = "+sex); System.out.println("Age = "+age); System.out.println("Branch = "+branch); } void TestMethod() // test what is valid to access { // name = "Mark"; Error: name is private sex = 'M'; RollNo = 20; } } What happens if super class constructor is not explicitly invoked ? (default constructor will be invoked).
  • 23. 23 Driver Class class MyTest { public static void main(String args[] ) { student s1 = new student("Rama", 'M', 21, 1, "Computer Science"); student s2 = new student("Sita", 'F', 19, 2, "Software Engineering"); System.out.println("Student 1 Details..."); s1.Display(); System.out.println("Student 2 Details..."); s2.Display(); person p1 = new person("Rao", 'M', 45); System.out.println("Person Details..."); p1.Display(); } } Can we create Object of person class ?
  • 24. 24 Output [raj@mundroo] inheritance [1:154] java MyTest Student 1 Details... Roll No = 1 Name = Rama Sex = M Age = 21 Branch = Computer Science Student 2 Details... Roll No = 2 Name = Sita Sex = F Age = 19 Branch = Software Engineering Person Details... Name = Rao Sex = M Age = 45 [raj@mundroo] inheritance [1:155]
  • 25. 25 Summary  Inheritance promotes reusability by supporting the creation of new classes from existing classes.  Various forms of inheritance can be realised in Java.  Child class constructor can be directed to invoke selected constructor from parent using super keyword.  Variables and Methods from parent classes can be overridden by redefining them in derived classes.  New Keywords: extends, super, final
  • 26. 26 References  Chapter 8: Sections 8.11, 8.12, 8.13, and 8.14 from Java book by Balagurusamy  Optional: <for in depth>  Chapter 14: Inheritance from “Mastering C++” by Venugopal and Buyya!