SlideShare a Scribd company logo
1 of 21
Download to read offline
Programming in Java
Lecture 7: Inheritance
By
Ravi Kant Sahu
Asst. Professor, LPU
Contents
 Inheritance
 Method Overloading
 Method Overriding
 Dynamic Method Dispatch
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Introduction
 Object-oriented programming allows classes to inherit
commonly used state and behavior from other classes.
 In the Java programming language, each class is allowed
to have one direct super-class, and each super-class has the
potential for an unlimited number of subclasses.
 Inheritance is a fundamental object-oriented design
technique used to create and organize reusable classes.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Inheritance
 Inheritance defines an is-a relationship between a super-class
and its subclasses. It means that the subclass (child) is a more
specific version of the super-class (parent).
 An object of a subclass can be used wherever an object of the
super-class can be used.
 Inheritance is used to build new classes from existing classes.
 The inheritance relationship is transitive: if class y extends
class x, and a class z extends class y, then z will also inherit
from class x.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Inheritance
 Using inheritance, we can create a general class that defines
traits(state and behaviors) common to a set of related items.
 This class can then be inherited by other, more specific classes,
each adding those things that are unique to it.
 In Java, a class that is inherited is called a super-class.
 The class that does the inheriting is called a subclass.
 A Subclass inherits all of the instance variables and methods
defined by the super-class and adds its own, unique elements.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Inheritance Example
class Shape {
int area(){…}
}
class Rectangle extends Shape{
int area() { area = length * width;}
int length; int width;
}
class Square extends Rectangle {
int area() {…}
int length; int width = length;
}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Key Points
 Private members of the super-class are inherited but they
can not be accessed by the subclass directly.
 Members that have default accessibility in the super-class
are also not inherited by subclasses in other packages.
 Constructors and initializer blocks are not inherited by a
subclass.
 A subclass can extend only one super-class.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Types of Inheritance
The following kinds of inheritance are there in java.
 Simple Inheritance
 Multilevel Inheritance
 Simple Inheritance: A subclass is derived simply from it's
parent class.
 There is only a sub class and it's parent class. It is also
called single inheritance or one level inheritance.
 Multi-level Inheritance: A subclass is derived from a
derived class.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Multiple Inheritance
 The mechanism of inheriting the features of more than one
base class into a single class is known as multiple
inheritance.
 Java does not support multiple inheritance but the
multiple inheritance can be achieved by using the
interface.
 In Java Multiple Inheritance can be achieved through use
of Interfaces by implementing more than one interfaces in
a class.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Method Overloading
 Method overloading means having two or more methods with
the same name but different signatures in the same scope.
 These two methods may exist in the same class or one in base
class and another in derived class.
 It allows creating several methods with the same name which
differ from each other in the type of the input and the output of
the method.
 It is simply defined as the ability of one method to perform
different tasks.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Example
class Area11
{
void area(int a)
{
int area = a*a;
System.out.println("area of square is:" + area);
}
void area (int a, int b)
{
int area = a*b;
System.out.println("area of rectangle is:" + area);
}
}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
class OverloadDemo
{
public static void main (String arr[])
{
Area11 ar= new Area11();
ar.area(10);
ar.area(10,5);
}
}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Method Overriding
 Method overriding means having a different implementation
of the same method in the inherited class.
 These two methods would have the same signature, but
different implementation.
 One of these would exist in the base class and another in the
derived class. These cannot exist in the same class.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
 The version of a method that is executed will be
determined by the object that is used to invoke it.
 If an object of a parent class is used to invoke the
method, then the version in the parent class will be
executed.
 If an object of the subclass is used to invoke the
method, then the version in the child class will be
executed.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
class Override
{
public void display()
{
System.out.println("Hello...This is superclass display");
}
}
class Override1 extends Override
{
public void display()
{
System.out.println("Hi...This is overriden method in subclass");
}
}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
class OverrideDemo
{
public static void main(String arr[])
{
Override o = new Override();
o.display();
Override1 o1 = new Override1();
o1.display();
}
}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Dynamic Method Dispatch
 Dynamic method dispatch is the mechanism by which a
call to an overridden method is resolved at run time, rather
than compile time.
 Dynamic method dispatch is important because this is
how Java implements run-time polymorphism.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
 class A {
void callme() {
System.out.println("Inside A's callme method");
}
}

class B extends A {
void callme() {
System.out.println("Inside B's callme method");
}
}
class C extends A {
void callme() {
System.out.println("Inside C's callme method");
}
}Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
class Dispatch {
public static void main(String args[]) {
A a = new A(); // object of type A
B b = new B(); // object of type B
C c = new C(); // object of type C
A r; // obtain a reference of type A
r = a; // r refers to an A object
r.callme(); // calls A's version of callme
r = b; // r refers to a B object
r.callme(); // calls B's version of callme
r = c; // r refers to a C object
r.callme(); // calls C's version of callme
}
}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Inheritance

More Related Content

What's hot

Common Programming Errors by Beginners in Java
Common Programming Errors by Beginners in JavaCommon Programming Errors by Beginners in Java
Common Programming Errors by Beginners in JavaRavi_Kant_Sahu
 
Abstract class and Interface
Abstract class and InterfaceAbstract class and Interface
Abstract class and InterfaceHaris Bin Zahid
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaCPD INDIA
 
Structure of java program diff c- cpp and java
Structure of java program  diff c- cpp and javaStructure of java program  diff c- cpp and java
Structure of java program diff c- cpp and javaMadishetty Prathibha
 
Distributed Programming (RMI)
Distributed Programming (RMI)Distributed Programming (RMI)
Distributed Programming (RMI)Ravi Kant Sahu
 
Java interfaces & abstract classes
Java interfaces & abstract classesJava interfaces & abstract classes
Java interfaces & abstract classesShreyans Pathak
 
Object Oriented Programing JAVA presentaion
Object Oriented Programing JAVA presentaionObject Oriented Programing JAVA presentaion
Object Oriented Programing JAVA presentaionPritom Chaki
 
Java interview questions 1
Java interview questions 1Java interview questions 1
Java interview questions 1Sherihan Anver
 
Interface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar SinghInterface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar Singhdheeraj_cse
 
OCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference CardOCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference CardHari kiran G
 
6. Exception Handling
6. Exception Handling6. Exception Handling
6. Exception HandlingNilesh Dalvi
 
Interface in java ,multiple inheritance in java, interface implementation
Interface in java ,multiple inheritance in java, interface implementationInterface in java ,multiple inheritance in java, interface implementation
Interface in java ,multiple inheritance in java, interface implementationHoneyChintal
 
Java interfaces
Java interfacesJava interfaces
Java interfacesjehan1987
 
OCA Java SE 8 Exam Chapter 1 Java Building Blocks
OCA Java SE 8 Exam Chapter 1 Java Building BlocksOCA Java SE 8 Exam Chapter 1 Java Building Blocks
OCA Java SE 8 Exam Chapter 1 Java Building Blocksİbrahim Kürce
 

What's hot (18)

Common Programming Errors by Beginners in Java
Common Programming Errors by Beginners in JavaCommon Programming Errors by Beginners in Java
Common Programming Errors by Beginners in Java
 
Abstract class and Interface
Abstract class and InterfaceAbstract class and Interface
Abstract class and Interface
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
 
Structure of java program diff c- cpp and java
Structure of java program  diff c- cpp and javaStructure of java program  diff c- cpp and java
Structure of java program diff c- cpp and java
 
Unit 3 Java
Unit 3 JavaUnit 3 Java
Unit 3 Java
 
Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
 
Distributed Programming (RMI)
Distributed Programming (RMI)Distributed Programming (RMI)
Distributed Programming (RMI)
 
Inheritance in Java
Inheritance in JavaInheritance in Java
Inheritance in Java
 
Java interfaces & abstract classes
Java interfaces & abstract classesJava interfaces & abstract classes
Java interfaces & abstract classes
 
Object Oriented Programing JAVA presentaion
Object Oriented Programing JAVA presentaionObject Oriented Programing JAVA presentaion
Object Oriented Programing JAVA presentaion
 
Java interview questions 1
Java interview questions 1Java interview questions 1
Java interview questions 1
 
Interface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar SinghInterface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar Singh
 
OCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference CardOCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference Card
 
6. Exception Handling
6. Exception Handling6. Exception Handling
6. Exception Handling
 
Interface in java ,multiple inheritance in java, interface implementation
Interface in java ,multiple inheritance in java, interface implementationInterface in java ,multiple inheritance in java, interface implementation
Interface in java ,multiple inheritance in java, interface implementation
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
OOP java
OOP javaOOP java
OOP java
 
OCA Java SE 8 Exam Chapter 1 Java Building Blocks
OCA Java SE 8 Exam Chapter 1 Java Building BlocksOCA Java SE 8 Exam Chapter 1 Java Building Blocks
OCA Java SE 8 Exam Chapter 1 Java Building Blocks
 

Viewers also liked (20)

Applets
AppletsApplets
Applets
 
Array
ArrayArray
Array
 
Exception handling
Exception handlingException handling
Exception handling
 
String handling(string buffer class)
String handling(string buffer class)String handling(string buffer class)
String handling(string buffer class)
 
Wrapper classes
Wrapper classesWrapper classes
Wrapper classes
 
Event handling
Event handlingEvent handling
Event handling
 
Packages
PackagesPackages
Packages
 
Multi threading
Multi threadingMulti threading
Multi threading
 
Inheritance in oops
Inheritance in oopsInheritance in oops
Inheritance in oops
 
2310 b 11
2310 b 112310 b 11
2310 b 11
 
Nosql availability & integrity
Nosql availability & integrityNosql availability & integrity
Nosql availability & integrity
 
Java swing
Java swingJava swing
Java swing
 
Perl Development
Perl DevelopmentPerl Development
Perl Development
 
2310 b 09
2310 b 092310 b 09
2310 b 09
 
Forms authentication
Forms authenticationForms authentication
Forms authentication
 
01 Ajax Intro
01 Ajax Intro01 Ajax Intro
01 Ajax Intro
 
PyCologne
PyColognePyCologne
PyCologne
 
Introduction To Silverlight and Prism
Introduction To Silverlight and PrismIntroduction To Silverlight and Prism
Introduction To Silverlight and Prism
 
Oid structure
Oid structureOid structure
Oid structure
 
5 Key Components of Genrocket
5 Key Components of Genrocket5 Key Components of Genrocket
5 Key Components of Genrocket
 

Similar to Inheritance

L7 inheritance
L7 inheritanceL7 inheritance
L7 inheritanceteach4uin
 
L7 inheritance
L7 inheritanceL7 inheritance
L7 inheritanceteach4uin
 
5. Inheritances, Packages and Intefaces
5. Inheritances, Packages and Intefaces5. Inheritances, Packages and Intefaces
5. Inheritances, Packages and IntefacesNilesh Dalvi
 
Inheritance in Java.pdf
Inheritance in Java.pdfInheritance in Java.pdf
Inheritance in Java.pdfkumari36
 
Inheritance ppt
Inheritance pptInheritance ppt
Inheritance pptNivegeetha
 
Inheritance in Java beginner to advance with examples.pptx
Inheritance in Java beginner to advance with examples.pptxInheritance in Java beginner to advance with examples.pptx
Inheritance in Java beginner to advance with examples.pptxnaeemcse
 
L22 multi-threading-introduction
L22 multi-threading-introductionL22 multi-threading-introduction
L22 multi-threading-introductionteach4uin
 
Control structures in Java
Control structures in JavaControl structures in Java
Control structures in JavaRavi_Kant_Sahu
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritanceArjun Shanka
 
Java Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overridingJava Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overridingNithyaN19
 
Unit3 inheritance
Unit3 inheritanceUnit3 inheritance
Unit3 inheritanceKalai Selvi
 

Similar to Inheritance (20)

Java keywords
Java keywordsJava keywords
Java keywords
 
L7 inheritance
L7 inheritanceL7 inheritance
L7 inheritance
 
L7 inheritance
L7 inheritanceL7 inheritance
L7 inheritance
 
Java beans
Java beansJava beans
Java beans
 
5. Inheritances, Packages and Intefaces
5. Inheritances, Packages and Intefaces5. Inheritances, Packages and Intefaces
5. Inheritances, Packages and Intefaces
 
Generics
GenericsGenerics
Generics
 
Inheritance in Java.pdf
Inheritance in Java.pdfInheritance in Java.pdf
Inheritance in Java.pdf
 
Inheritance ppt
Inheritance pptInheritance ppt
Inheritance ppt
 
Collection framework
Collection frameworkCollection framework
Collection framework
 
Inheritance in Java beginner to advance with examples.pptx
Inheritance in Java beginner to advance with examples.pptxInheritance in Java beginner to advance with examples.pptx
Inheritance in Java beginner to advance with examples.pptx
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
L22 multi-threading-introduction
L22 multi-threading-introductionL22 multi-threading-introduction
L22 multi-threading-introduction
 
Suga java training_with_footer
Suga java training_with_footerSuga java training_with_footer
Suga java training_with_footer
 
Control structures in Java
Control structures in JavaControl structures in Java
Control structures in Java
 
Inheritance
InheritanceInheritance
Inheritance
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritance
 
Chap11
Chap11Chap11
Chap11
 
Java Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overridingJava Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overriding
 
Unit3 inheritance
Unit3 inheritanceUnit3 inheritance
Unit3 inheritance
 
inheritance.pptx
inheritance.pptxinheritance.pptx
inheritance.pptx
 

More from Ravi_Kant_Sahu

More from Ravi_Kant_Sahu (7)

Event handling
Event handlingEvent handling
Event handling
 
List classes
List classesList classes
List classes
 
String handling(string class)
String handling(string class)String handling(string class)
String handling(string class)
 
Jdbc
JdbcJdbc
Jdbc
 
Operators in java
Operators in javaOperators in java
Operators in java
 
Swing api
Swing apiSwing api
Swing api
 
Genesis and Overview of Java
Genesis and Overview of Java Genesis and Overview of Java
Genesis and Overview of Java
 

Recently uploaded

"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 

Recently uploaded (20)

"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 

Inheritance

  • 1. Programming in Java Lecture 7: Inheritance By Ravi Kant Sahu Asst. Professor, LPU
  • 2. Contents  Inheritance  Method Overloading  Method Overriding  Dynamic Method Dispatch Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 3. Introduction  Object-oriented programming allows classes to inherit commonly used state and behavior from other classes.  In the Java programming language, each class is allowed to have one direct super-class, and each super-class has the potential for an unlimited number of subclasses.  Inheritance is a fundamental object-oriented design technique used to create and organize reusable classes. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 4. Inheritance  Inheritance defines an is-a relationship between a super-class and its subclasses. It means that the subclass (child) is a more specific version of the super-class (parent).  An object of a subclass can be used wherever an object of the super-class can be used.  Inheritance is used to build new classes from existing classes.  The inheritance relationship is transitive: if class y extends class x, and a class z extends class y, then z will also inherit from class x. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 5. Inheritance  Using inheritance, we can create a general class that defines traits(state and behaviors) common to a set of related items.  This class can then be inherited by other, more specific classes, each adding those things that are unique to it.  In Java, a class that is inherited is called a super-class.  The class that does the inheriting is called a subclass.  A Subclass inherits all of the instance variables and methods defined by the super-class and adds its own, unique elements. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 6. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 7. Inheritance Example class Shape { int area(){…} } class Rectangle extends Shape{ int area() { area = length * width;} int length; int width; } class Square extends Rectangle { int area() {…} int length; int width = length; } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 8. Key Points  Private members of the super-class are inherited but they can not be accessed by the subclass directly.  Members that have default accessibility in the super-class are also not inherited by subclasses in other packages.  Constructors and initializer blocks are not inherited by a subclass.  A subclass can extend only one super-class. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 9. Types of Inheritance The following kinds of inheritance are there in java.  Simple Inheritance  Multilevel Inheritance  Simple Inheritance: A subclass is derived simply from it's parent class.  There is only a sub class and it's parent class. It is also called single inheritance or one level inheritance.  Multi-level Inheritance: A subclass is derived from a derived class. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 10. Multiple Inheritance  The mechanism of inheriting the features of more than one base class into a single class is known as multiple inheritance.  Java does not support multiple inheritance but the multiple inheritance can be achieved by using the interface.  In Java Multiple Inheritance can be achieved through use of Interfaces by implementing more than one interfaces in a class. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 11. Method Overloading  Method overloading means having two or more methods with the same name but different signatures in the same scope.  These two methods may exist in the same class or one in base class and another in derived class.  It allows creating several methods with the same name which differ from each other in the type of the input and the output of the method.  It is simply defined as the ability of one method to perform different tasks. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 12. Example class Area11 { void area(int a) { int area = a*a; System.out.println("area of square is:" + area); } void area (int a, int b) { int area = a*b; System.out.println("area of rectangle is:" + area); } } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 13. class OverloadDemo { public static void main (String arr[]) { Area11 ar= new Area11(); ar.area(10); ar.area(10,5); } } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 14. Method Overriding  Method overriding means having a different implementation of the same method in the inherited class.  These two methods would have the same signature, but different implementation.  One of these would exist in the base class and another in the derived class. These cannot exist in the same class. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 15.  The version of a method that is executed will be determined by the object that is used to invoke it.  If an object of a parent class is used to invoke the method, then the version in the parent class will be executed.  If an object of the subclass is used to invoke the method, then the version in the child class will be executed. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 16. class Override { public void display() { System.out.println("Hello...This is superclass display"); } } class Override1 extends Override { public void display() { System.out.println("Hi...This is overriden method in subclass"); } } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 17. class OverrideDemo { public static void main(String arr[]) { Override o = new Override(); o.display(); Override1 o1 = new Override1(); o1.display(); } } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 18. Dynamic Method Dispatch  Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at run time, rather than compile time.  Dynamic method dispatch is important because this is how Java implements run-time polymorphism. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 19.  class A { void callme() { System.out.println("Inside A's callme method"); } }  class B extends A { void callme() { System.out.println("Inside B's callme method"); } } class C extends A { void callme() { System.out.println("Inside C's callme method"); } }Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 20. class Dispatch { public static void main(String args[]) { A a = new A(); // object of type A B b = new B(); // object of type B C c = new C(); // object of type C A r; // obtain a reference of type A r = a; // r refers to an A object r.callme(); // calls A's version of callme r = b; // r refers to a B object r.callme(); // calls B's version of callme r = c; // r refers to a C object r.callme(); // calls C's version of callme } } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)