SlideShare a Scribd company logo
1 of 16
Inheritance: A brief recap 
• Inheritance is of 4 types: Single, Multilevel, Multiple 
and Hybrid( also known as hierarchical). 
• Java does not support Multiple inheritance with 
sohamsengupta@yahoo.com 1 
classes. 
• In java, if a class A inherits from another class B, the 
syntax is going to be : 
class A extends B 
{ 
// codes ( data & method & blocks if any) 
}
More on Inheritance 
• Here class A is called the child/ derived class 
• Class B is called the base/parent class 
• With respect to the child class, the base class is 
referred to as “super”. 
• All non-private data and method are inherited 
from the base class to the derived or child class. 
• Inheritance bears the polymorphism concept 
that incorporates the code reusability and 
method overriding paradigms. 
sohamsengupta@yahoo.com 2
Sample Code Snippet 
class Base 
{ 
int x=940; 
static int percentage=94; 
void show(){ 
System.out.println(“Your score is ”+x); 
} 
} 
class Child extends Base 
{ 
int y=89; 
void display(){ 
System.out.println("My parent's score was "+x); // x is now available here 
System.out.println("My parent's score was "+super.x); // x is accessible by super 
System.out.println("My parent's score was "+this.x); // x is now available here 
System.out.println(“Parent’s percentage can be expressed as ”+percentage+ “,”+Base.percentage+ 
“,”+Child.percentage+ “,”+super.percentage); 
System.out.println(“I’m child with marks “+y); 
} 
} 
class A 
{ 
public static void main(String[] args){ 
Child ch=new Child(); 
ch.show(); // show in Base available to Child 
ch.display(); 
} 
} 
sohamsengupta@yahoo.com 3
When a child-class field has name as that of one in the base class 
class Base 
{ 
int x=940; 
} 
class Child extends Base 
{ 
int x=719; 
void show(){ 
System.out.println("My marks is "+x); 
System.out.println("Parent's marks was "+super.x); 
} 
}// super.x denotes Base-class data. Methods in child class with same name 
//can be accessed likewise 
class A 
{ 
public static void main(String[] args){ 
Child ch=new Child(); 
ch.show(); 
} 
} // keyword “super” cannot be accessed from within static context. 
sohamsengupta@yahoo.com 4
Role of Constructors in Inheritance 
class Base 
{ 
Base(){ 
System.out.println("From Base Constructor"); 
} 
} 
class Child extends Base 
{ 
Child(){ 
System.out.println("From Child Constructor"); 
} 
} 
class A 
{ 
public static void main(String[] args){ 
Child ch=new Child(); 
} 
} 
When the child class constructor is invoked, the following 
steps take place behind the scene… 
1. The static blocks and initializers in the Base class 
execute when the class is loaded into memory 
followed by the same in the Child class 
2. Now for each object of Child class, first the non-static 
blocks and constructor of base class execute 
3. Then those in the child class execute. 
FAQ: 
1. We are not calling the base-class constructor, then how 
come the base-class constructor is invoked? 
Answer: See, although the call isn’t explicit, there is an 
implicit call to super(), the default/no-arg Base class 
Constructor at the very first line in Child(). 
However, if there is not any no-arg constructor in the base 
class it’ll be an error (Onto next slide) 
sohamsengupta@yahoo.com 5
super() constructor 
class Base 
{ 
Base(int x){ 
System.out.println("From Base Constructor "+x); 
} 
} 
class Child extends Base 
{ 
Child(){ // Error super() not found; call super(940); 
System.out.println("From Child Constructor"); 
} 
} 
class A // call to super constructor must be the very 1st line in child constructor 
else won’t compile 
{ 
public static void main(String[] args){ 
Child ch=new Child(); 
} 
} 
sohamsengupta@yahoo.com 6
Method overriding 
1. If a child class redefines an inherited method 
present in the Base class, it’s known as a case of 
overriding and the method in the base class is 
said to have been overridden in subclass. 
2. private methods can never be overridden since 
they are not inherited. 
3. static methods can never be inherited. 
4. overriding cannot impose more restrictive access 
on the method 
5. Its parameter list is kept unchanged. 
6. Return type generally same.( details later) 
7. Can never declare to throw broader checked 
Exceptions. (More on this later) 
8. Method overriding is Runtime Polymorphism. 
sohamsengupta@yahoo.com 7
An example of method overriding 
sohamsengupta@yahoo.com 8 
class Base 
{ 
void show(){ 
System.out.println("Hello"); 
} 
} 
class Child extends Base 
{ 
void show(){ 
System.out.println("Born!"); 
} 
} 
class A 
{ 
public static void main(String[] args){ 
Base ref=new Base(); 
ref.show(); // output: Hello 
ref=new Child(); // the ref to Base can hold obj of 
// Child 
//But converse isn't true without explicit type cast. 
// type cast may turn out to be fatal 
//ClassCastException depending on code 
ref.show(); // output: Born! it's because, the 
// ref although being a reference of Base, holds 
//object of Child 
// this is runtime( ? ) polymorphism or dynamic 
method dispatch 
} 
}
static methods can’t be overridden 
sohamsengupta@yahoo.com 9 
class Base 
{ 
static void show(){ 
System.out.println("Hello"); 
} 
} 
class Child extends Base 
{ 
void show(){ 
System.out.println("Born!"); 
} 
} 
// Error… to avoid: either both should be 
static or neither should. Well, let’s make 
both static. Now it compiles. But 
overriding is not possible. Create an 
object of Child and store to a Base’s 
reference. Call the method show(). But 
Dynamic method dispatch is never seen. 
class A 
{ 
public static void main(String[] rt){ 
Base ref=new Child(); 
ref.show(); 
} 
} 
Output: Hello. 
So, static methods are not overridden as 
they don’t follow the rule of dynamic 
method dispatch
Why overriding can’t impose more restrictive access? 
Assume, if it were possible, the method show() 
in default access-specifier in class Base is 
overridden in class Child to be private. OK up to 
this! 
Now just think of dynamic method dispatch 
where the decision to call which version of the 
method is taken at runtime. So, the code will 
compile. But, poor Programmer! He/she hardly 
knew that this won’t work since the method is 
imposed private access in Child class. This will 
make to code inconsistent in every aspect. 
sohamsengupta@yahoo.com 10
Why no multiple Inheritance in Java ? 
Assume a class A has 2 subclasses B and C 
and that each overrides a method, say, 
method1() and also assume that if multiple 
inheritance were possible, a class D extending 
both B and C. So, question will arise which of 
the implementations of the same method will the 
class D inherit? This is a fallacy. This is known 
as the “Deadly Diamond of Death” problem 
sohamsengupta@yahoo.com 11
More on Inheritance 
 if you add the keyword “final” before a method 
it can’t be anymore overridden. 
If it’s used with a class, the class can’t be 
anymore inherited or sub-classed. 
In order of decreasing restriction, the access 
specifiers are private, default, protected and 
public 
So far we’ve covered only access specifiers with 
methods and data but not with class itself. We’ll 
see it shortly. 
sohamsengupta@yahoo.com 12
Abstract Methods & Classes 
 An abstract method is one, which does not declare any 
body. Eg. abstract void show(); 
 An abstract class is one which has the keyword abstract 
associated with its declaration. We can’t create objects 
of abstract classes due to compilation errors. 
 Abstract classes may have constructors. 
 If a class contains at least one abstract method, it must 
be declared abstract. But an abstract class may have no 
abstract methods at all. 
 Any class that inherits an abstract class, will either 
define all the inherited abstract methods, if any, or be 
itself declared abstract. 
 The keyword “final” does not apply with the keyword 
“abstract”. Also an abstract method can’t be private. 
 The reference to Base can hold object of Child. But here 
basrRef can’t access methods which are not in Base. 
sohamsengupta@yahoo.com 13
iinnssttaanncceeooff ooppeerraattoorr 
 It’s a binary operator taking first operand as a 
reference of a class and the second as a class name 
itself. 
If the object contained by the reference is of the second 
operand class type or a sub type, it returns true else 
false. 
If the reference and class name are not bound by single 
or multilevel inheritance hierarchy, compilation error 
occurs complaining of inconvertible or incompatible 
types. 
Java.lang.Object is the Universal superclass. Every 
class inherits from Object clas 
 An Example of instanceof operator 
sohamsengupta@yahoo.com 14
sohamsengupta@yahoo.com 15 
class B1 
{} 
class B2 extends B1 
{} 
class B3 extends B1 
{} 
class A 
{ 
public static void main(String[] args){ 
B1 b1=new B1(); 
B2 b2=new B2(); 
B3 b3=new B3(); 
System.out.println(b1 instanceof B1); // true 
System.out.println(b2 instanceof B1); // true 
System.out.println(b3 instanceof B1); // true 
System.out.println(b1 instanceof B2); // false 
b1=new B2(); 
System.out.println(null instanceof B1);// false 
System.out.println(b1 instanceof Object); // true 
System.out.println(b1 instanceof B2); // true 
// System.out.println(b3 instanceof B2); Error 
}}
Overloading Versus Overriding 
• Exhibited inside a class 
• Return type can be different 
and does not play any role 
• Compile time polymorphism. 
• Parameters must be different 
in regard of type, number, 
and/or order. 
• No restriction imposed on 
declaring Exceptions 
• Reference Arguments are 
passed depending on the type 
of reference not the object it 
refers to. 
• Can’t be generally prevented. 
• Requires both Base & Child 
class 
• The overridden method must 
have return type either same 
or super type of the overrider 
method. 
• Runtime plymorphism 
• Parameters must be same. 
• Cannot declare to throw 
broader checked 
exceptions( details later) 
• Dynamic method dispatch is 
dependent on the type of the 
object not the reference type. 
• We can prevent overriding by 
declaring the method to be 
final. 
sohamsengupta@yahoo.com 16

More Related Content

What's hot

9781111530532 ppt ch10
9781111530532 ppt ch109781111530532 ppt ch10
9781111530532 ppt ch10Terry Yoast
 
Object oriented programming in php 5
Object oriented programming in php 5Object oriented programming in php 5
Object oriented programming in php 5Sayed Ahmed
 
Lecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops conceptLecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops conceptmanish kumar
 
Java Classes methods and inheritance
Java Classes methods and inheritanceJava Classes methods and inheritance
Java Classes methods and inheritanceSrinivas Reddy
 
Java Inheritance
Java InheritanceJava Inheritance
Java InheritanceVINOTH R
 
Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...
Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...
Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...Ayes Chinmay
 
Introduction to object oriented programming concepts
Introduction to object oriented programming conceptsIntroduction to object oriented programming concepts
Introduction to object oriented programming conceptsGanesh Karthik
 
Lecture 6 inheritance
Lecture   6 inheritanceLecture   6 inheritance
Lecture 6 inheritancemanish kumar
 
Inheritance in java
Inheritance in java Inheritance in java
Inheritance in java yash jain
 
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...Ayes Chinmay
 
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
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in javaTech_MX
 
Synapseindia strcture of dotnet development part 1
Synapseindia strcture of dotnet development part 1Synapseindia strcture of dotnet development part 1
Synapseindia strcture of dotnet development part 1Synapseindiappsdevelopment
 
Unit 4 exceptions and threads
Unit 4 exceptions and threadsUnit 4 exceptions and threads
Unit 4 exceptions and threadsDevaKumari Vijay
 
Lecture 4_Java Method-constructor_imp_keywords
Lecture   4_Java Method-constructor_imp_keywordsLecture   4_Java Method-constructor_imp_keywords
Lecture 4_Java Method-constructor_imp_keywordsmanish kumar
 

What's hot (20)

9781111530532 ppt ch10
9781111530532 ppt ch109781111530532 ppt ch10
9781111530532 ppt ch10
 
Object oriented programming in php 5
Object oriented programming in php 5Object oriented programming in php 5
Object oriented programming in php 5
 
Lecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops conceptLecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops concept
 
Java Classes methods and inheritance
Java Classes methods and inheritanceJava Classes methods and inheritance
Java Classes methods and inheritance
 
Java Inheritance
Java InheritanceJava Inheritance
Java Inheritance
 
Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...
Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...
Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...
 
Introduction to object oriented programming concepts
Introduction to object oriented programming conceptsIntroduction to object oriented programming concepts
Introduction to object oriented programming concepts
 
Lecture 6 inheritance
Lecture   6 inheritanceLecture   6 inheritance
Lecture 6 inheritance
 
Java tutorial part 2
Java tutorial part 2Java tutorial part 2
Java tutorial part 2
 
Unit3 part2-inheritance
Unit3 part2-inheritanceUnit3 part2-inheritance
Unit3 part2-inheritance
 
Reflection
ReflectionReflection
Reflection
 
Inheritance in java
Inheritance in java Inheritance in java
Inheritance in java
 
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
 
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
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Java reflection
Java reflectionJava reflection
Java reflection
 
Java Reflection
Java ReflectionJava Reflection
Java Reflection
 
Synapseindia strcture of dotnet development part 1
Synapseindia strcture of dotnet development part 1Synapseindia strcture of dotnet development part 1
Synapseindia strcture of dotnet development part 1
 
Unit 4 exceptions and threads
Unit 4 exceptions and threadsUnit 4 exceptions and threads
Unit 4 exceptions and threads
 
Lecture 4_Java Method-constructor_imp_keywords
Lecture   4_Java Method-constructor_imp_keywordsLecture   4_Java Method-constructor_imp_keywords
Lecture 4_Java Method-constructor_imp_keywords
 

Similar to Java Inheritance Types and Concepts

Similar to Java Inheritance Types and Concepts (20)

Chap-3 Inheritance.pptx
Chap-3 Inheritance.pptxChap-3 Inheritance.pptx
Chap-3 Inheritance.pptx
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
 
Inheritance Slides
Inheritance SlidesInheritance Slides
Inheritance Slides
 
Object oriented concepts
Object oriented conceptsObject oriented concepts
Object oriented concepts
 
Java assignment help
Java assignment helpJava assignment help
Java assignment help
 
INHERTANCE , NARROW AND WIDENING
INHERTANCE , NARROW AND WIDENING INHERTANCE , NARROW AND WIDENING
INHERTANCE , NARROW AND WIDENING
 
Java
JavaJava
Java
 
Java Basic day-2
Java Basic day-2Java Basic day-2
Java Basic day-2
 
Inheritance
InheritanceInheritance
Inheritance
 
java tutorial 3
 java tutorial 3 java tutorial 3
java tutorial 3
 
Introduction to OOP(in java) BY Govind Singh
Introduction to OOP(in java)  BY Govind SinghIntroduction to OOP(in java)  BY Govind Singh
Introduction to OOP(in java) BY Govind Singh
 
inheritance.pptx
inheritance.pptxinheritance.pptx
inheritance.pptx
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritance
 
Unit3 inheritance
Unit3 inheritanceUnit3 inheritance
Unit3 inheritance
 
Polymorphism in C# Function overloading in C#
Polymorphism in C# Function overloading in C#Polymorphism in C# Function overloading in C#
Polymorphism in C# Function overloading in C#
 
Lecture 14 (inheritance basics)
Lecture 14 (inheritance basics)Lecture 14 (inheritance basics)
Lecture 14 (inheritance basics)
 
Inheritance
InheritanceInheritance
Inheritance
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
 
lecture 6.pdf
lecture 6.pdflecture 6.pdf
lecture 6.pdf
 

More from Soham Sengupta

More from Soham Sengupta (20)

Spring method-level-secuirty
Spring method-level-secuirtySpring method-level-secuirty
Spring method-level-secuirty
 
Spring security mvc-1
Spring security mvc-1Spring security mvc-1
Spring security mvc-1
 
JavaScript event handling assignment
JavaScript  event handling assignment JavaScript  event handling assignment
JavaScript event handling assignment
 
Networking assignment 2
Networking assignment 2Networking assignment 2
Networking assignment 2
 
Networking assignment 1
Networking assignment 1Networking assignment 1
Networking assignment 1
 
Sohams cryptography basics
Sohams cryptography basicsSohams cryptography basics
Sohams cryptography basics
 
Network programming1
Network programming1Network programming1
Network programming1
 
JSR-82 Bluetooth tutorial
JSR-82 Bluetooth tutorialJSR-82 Bluetooth tutorial
JSR-82 Bluetooth tutorial
 
Xmpp and java
Xmpp and javaXmpp and java
Xmpp and java
 
Core java day2
Core java day2Core java day2
Core java day2
 
Core java day1
Core java day1Core java day1
Core java day1
 
Core java day4
Core java day4Core java day4
Core java day4
 
Exceptions
ExceptionsExceptions
Exceptions
 
Java.lang.object
Java.lang.objectJava.lang.object
Java.lang.object
 
Jsp1
Jsp1Jsp1
Jsp1
 
Soham web security
Soham web securitySoham web security
Soham web security
 
Html tables and_javascript
Html tables and_javascriptHtml tables and_javascript
Html tables and_javascript
 
Html javascript
Html javascriptHtml javascript
Html javascript
 
Java script
Java scriptJava script
Java script
 
Sohamsg ajax
Sohamsg ajaxSohamsg ajax
Sohamsg ajax
 

Recently uploaded

HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 

Recently uploaded (20)

HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 

Java Inheritance Types and Concepts

  • 1. Inheritance: A brief recap • Inheritance is of 4 types: Single, Multilevel, Multiple and Hybrid( also known as hierarchical). • Java does not support Multiple inheritance with sohamsengupta@yahoo.com 1 classes. • In java, if a class A inherits from another class B, the syntax is going to be : class A extends B { // codes ( data & method & blocks if any) }
  • 2. More on Inheritance • Here class A is called the child/ derived class • Class B is called the base/parent class • With respect to the child class, the base class is referred to as “super”. • All non-private data and method are inherited from the base class to the derived or child class. • Inheritance bears the polymorphism concept that incorporates the code reusability and method overriding paradigms. sohamsengupta@yahoo.com 2
  • 3. Sample Code Snippet class Base { int x=940; static int percentage=94; void show(){ System.out.println(“Your score is ”+x); } } class Child extends Base { int y=89; void display(){ System.out.println("My parent's score was "+x); // x is now available here System.out.println("My parent's score was "+super.x); // x is accessible by super System.out.println("My parent's score was "+this.x); // x is now available here System.out.println(“Parent’s percentage can be expressed as ”+percentage+ “,”+Base.percentage+ “,”+Child.percentage+ “,”+super.percentage); System.out.println(“I’m child with marks “+y); } } class A { public static void main(String[] args){ Child ch=new Child(); ch.show(); // show in Base available to Child ch.display(); } } sohamsengupta@yahoo.com 3
  • 4. When a child-class field has name as that of one in the base class class Base { int x=940; } class Child extends Base { int x=719; void show(){ System.out.println("My marks is "+x); System.out.println("Parent's marks was "+super.x); } }// super.x denotes Base-class data. Methods in child class with same name //can be accessed likewise class A { public static void main(String[] args){ Child ch=new Child(); ch.show(); } } // keyword “super” cannot be accessed from within static context. sohamsengupta@yahoo.com 4
  • 5. Role of Constructors in Inheritance class Base { Base(){ System.out.println("From Base Constructor"); } } class Child extends Base { Child(){ System.out.println("From Child Constructor"); } } class A { public static void main(String[] args){ Child ch=new Child(); } } When the child class constructor is invoked, the following steps take place behind the scene… 1. The static blocks and initializers in the Base class execute when the class is loaded into memory followed by the same in the Child class 2. Now for each object of Child class, first the non-static blocks and constructor of base class execute 3. Then those in the child class execute. FAQ: 1. We are not calling the base-class constructor, then how come the base-class constructor is invoked? Answer: See, although the call isn’t explicit, there is an implicit call to super(), the default/no-arg Base class Constructor at the very first line in Child(). However, if there is not any no-arg constructor in the base class it’ll be an error (Onto next slide) sohamsengupta@yahoo.com 5
  • 6. super() constructor class Base { Base(int x){ System.out.println("From Base Constructor "+x); } } class Child extends Base { Child(){ // Error super() not found; call super(940); System.out.println("From Child Constructor"); } } class A // call to super constructor must be the very 1st line in child constructor else won’t compile { public static void main(String[] args){ Child ch=new Child(); } } sohamsengupta@yahoo.com 6
  • 7. Method overriding 1. If a child class redefines an inherited method present in the Base class, it’s known as a case of overriding and the method in the base class is said to have been overridden in subclass. 2. private methods can never be overridden since they are not inherited. 3. static methods can never be inherited. 4. overriding cannot impose more restrictive access on the method 5. Its parameter list is kept unchanged. 6. Return type generally same.( details later) 7. Can never declare to throw broader checked Exceptions. (More on this later) 8. Method overriding is Runtime Polymorphism. sohamsengupta@yahoo.com 7
  • 8. An example of method overriding sohamsengupta@yahoo.com 8 class Base { void show(){ System.out.println("Hello"); } } class Child extends Base { void show(){ System.out.println("Born!"); } } class A { public static void main(String[] args){ Base ref=new Base(); ref.show(); // output: Hello ref=new Child(); // the ref to Base can hold obj of // Child //But converse isn't true without explicit type cast. // type cast may turn out to be fatal //ClassCastException depending on code ref.show(); // output: Born! it's because, the // ref although being a reference of Base, holds //object of Child // this is runtime( ? ) polymorphism or dynamic method dispatch } }
  • 9. static methods can’t be overridden sohamsengupta@yahoo.com 9 class Base { static void show(){ System.out.println("Hello"); } } class Child extends Base { void show(){ System.out.println("Born!"); } } // Error… to avoid: either both should be static or neither should. Well, let’s make both static. Now it compiles. But overriding is not possible. Create an object of Child and store to a Base’s reference. Call the method show(). But Dynamic method dispatch is never seen. class A { public static void main(String[] rt){ Base ref=new Child(); ref.show(); } } Output: Hello. So, static methods are not overridden as they don’t follow the rule of dynamic method dispatch
  • 10. Why overriding can’t impose more restrictive access? Assume, if it were possible, the method show() in default access-specifier in class Base is overridden in class Child to be private. OK up to this! Now just think of dynamic method dispatch where the decision to call which version of the method is taken at runtime. So, the code will compile. But, poor Programmer! He/she hardly knew that this won’t work since the method is imposed private access in Child class. This will make to code inconsistent in every aspect. sohamsengupta@yahoo.com 10
  • 11. Why no multiple Inheritance in Java ? Assume a class A has 2 subclasses B and C and that each overrides a method, say, method1() and also assume that if multiple inheritance were possible, a class D extending both B and C. So, question will arise which of the implementations of the same method will the class D inherit? This is a fallacy. This is known as the “Deadly Diamond of Death” problem sohamsengupta@yahoo.com 11
  • 12. More on Inheritance  if you add the keyword “final” before a method it can’t be anymore overridden. If it’s used with a class, the class can’t be anymore inherited or sub-classed. In order of decreasing restriction, the access specifiers are private, default, protected and public So far we’ve covered only access specifiers with methods and data but not with class itself. We’ll see it shortly. sohamsengupta@yahoo.com 12
  • 13. Abstract Methods & Classes  An abstract method is one, which does not declare any body. Eg. abstract void show();  An abstract class is one which has the keyword abstract associated with its declaration. We can’t create objects of abstract classes due to compilation errors.  Abstract classes may have constructors.  If a class contains at least one abstract method, it must be declared abstract. But an abstract class may have no abstract methods at all.  Any class that inherits an abstract class, will either define all the inherited abstract methods, if any, or be itself declared abstract.  The keyword “final” does not apply with the keyword “abstract”. Also an abstract method can’t be private.  The reference to Base can hold object of Child. But here basrRef can’t access methods which are not in Base. sohamsengupta@yahoo.com 13
  • 14. iinnssttaanncceeooff ooppeerraattoorr  It’s a binary operator taking first operand as a reference of a class and the second as a class name itself. If the object contained by the reference is of the second operand class type or a sub type, it returns true else false. If the reference and class name are not bound by single or multilevel inheritance hierarchy, compilation error occurs complaining of inconvertible or incompatible types. Java.lang.Object is the Universal superclass. Every class inherits from Object clas  An Example of instanceof operator sohamsengupta@yahoo.com 14
  • 15. sohamsengupta@yahoo.com 15 class B1 {} class B2 extends B1 {} class B3 extends B1 {} class A { public static void main(String[] args){ B1 b1=new B1(); B2 b2=new B2(); B3 b3=new B3(); System.out.println(b1 instanceof B1); // true System.out.println(b2 instanceof B1); // true System.out.println(b3 instanceof B1); // true System.out.println(b1 instanceof B2); // false b1=new B2(); System.out.println(null instanceof B1);// false System.out.println(b1 instanceof Object); // true System.out.println(b1 instanceof B2); // true // System.out.println(b3 instanceof B2); Error }}
  • 16. Overloading Versus Overriding • Exhibited inside a class • Return type can be different and does not play any role • Compile time polymorphism. • Parameters must be different in regard of type, number, and/or order. • No restriction imposed on declaring Exceptions • Reference Arguments are passed depending on the type of reference not the object it refers to. • Can’t be generally prevented. • Requires both Base & Child class • The overridden method must have return type either same or super type of the overrider method. • Runtime plymorphism • Parameters must be same. • Cannot declare to throw broader checked exceptions( details later) • Dynamic method dispatch is dependent on the type of the object not the reference type. • We can prevent overriding by declaring the method to be final. sohamsengupta@yahoo.com 16