SlideShare a Scribd company logo
1 of 33
CHAPTER 3 INHERITANCE
By
Sirage Zeynu (M.Tech)
School of Computing
13-04-2021 INHERITANCE 2
Outline of this chapter
1.Concept of inheritance
2.Super classes and subclasses
3.Protected members
4.Overriding methods
5.Using this () and super ()
6.Use of final with inheritance
7.Constructors in subclasses
13-04-2021 INHERITANCE 3
What is Inheritance ?
Inheritance is one of the cornerstones of object-oriented programming
because it allows the creation of hierarchical classifications.
In Java, classes can be derived from classes.
Basically, if you need to create a new class and here is already a class
that has some of the code you require, then it is possible to derive your
new class from the already existing code.
This concept allows you to reuse the fields and methods of the existing
class without having to rewrite the code in a new class. In this scenario,
the existing class is called the superclass and the derived class is called
the subclass.
To inherit a class, you simply incorporate the definition of one class into
another by using the extends keyword.
13-04-2021 INHERITANCE 4
Inheritance is one such concept where the properties of one class
can be inherited by the other.
It helps to reuse the code and establish a relationship between
different classes.
extends Keyword
extends is the keyword used to inherit the properties of a class.
Following is the syntax of extends keyword.
class Super{
.....
..... }
class Sub extends Super {
..... .....
}
13-04-2021 INHERITANCE 5
A simple example of inheritance
13-04-2021 INHERITANCE 6
13-04-2021 INHERITANCE 7
 Inheritance relationships form tree-like hierarchical structures.
 A superclass exists in a hierarchical relationship with its
subclasses.
 When classes participate in inheritance relationships, they
become “affiliated” with other classes.
 A class becomes either a superclass, supplying members to
other classes, or a subclass, inheriting its members from other
classes
 note that super classes tend to be “more general” and
subclasses “more specific.”
Super classes and Subclasses
13-04-2021 INHERITANCE 8
Super class
(base/parent/driver/inheritance/ ancestor class).
Intermediate class
(mediating/dual class).
Child class
(sub/associate/derived/inherited class).
13-04-2021 INHERITANCE 9
 A superclass’s public members are accessible anywhere the
program has a reference to that superclass type or one of its
subclass types.
 A superclass’s private members are accessible only in methods
of that superclass.
 A superclass’s protected members may be accessed only by
methods of the superclass, by methods of subclasses and by
methods of other classes in the same package (protected
members have package access).
 Subclass methods can normally refer to public and protected
members of the superclass simply by using the member names.
Member Access and Inheritance
13-04-2021 INHERITANCE 10
class Access {
public static void main ( String
args[ ] ) {
B subob = new B ( );
subob.setij (10, 12 );
subob.sum( );
System.out.println ( “ Total is “ +
subob.total );
}}
class A {
int i; // public by default
private int j; // private to A
void setij ( int x, int y) {
i = x;
j = y;
}}
// A’s j is not accessible here
class B extends A {
int total ;
void sum ( ) {
total =i + j ; // Error, j is not accessible here
}}
/ * In a class hierarchy, private members remain private to their class.
This program contains an error and will not compile */
13-04-2021 INHERITANCE 11
 The super keyword is similar to this keyword.
Following are the scenarios where the super keyword is used.
 It is used to differentiate the members of super class from
the members of sub class, if they have same names.
 It is used to invoke the super class constructor from subclass.
 If a class is inheriting the properties of another class. And if
the members of the superclass have the names same as the sub
class, to differentiate these variables we use super keyword.
The super keyword
13-04-2021 INHERITANCE 12
13-04-2021 INHERITANCE 13
13-04-2021 INHERITANCE 14
Output of the above program
13-04-2021 INHERITANCE 15
 A subclass can call a constructor method defined by its
superclass by use of the following form of super.
super ( parameter-list );
 Here, parameter-list specifies any parameters needed by the
constructor in the superclass.
 super ( ) must always be the first statement executer inside a
subclass constructor.
Using super to call superclass Constructor
13-04-2021 INHERITANCE 16
13-04-2021 INHERITANCE 17
 The first thing a subclass constructor must do is call the
superclass constructor
 This ensures that the superclass part of the object is
constructed before the subclass part
 If you do not call the superclass constructor with the super
keyword, and the superclass has a constructor with no
arguments, then that superclass constructor will be called
implicitly.
Subclass Constructor
Implicit Super Constructor Call
If I have this Food class:
public class Food {
private boolean raw;
public Food() {
raw = true;
}
}
then this Beef subclass:
public class Beef extends Food {
private double weight;
public Beef(double w) {
weight = w
}}
is equivalent to:
public class Beef extends Food {
private double weight;
public Beef(double w) {
super();
weight = w
}
}
13-04-2021 INHERITANCE 19
The this keyword
 A special reference value called this is included in Java .
 The this keyword is used inside any instance method to refer to
the current object .
 The value this refers to the object which the current method
has been called on .
 The this keyword can be used where a reference to an object of
the current class type is required .
13-04-2021 INHERITANCE 20
The following example illustrates the usage of the keyword this.
The output appear as given below :
13-04-2021 INHERITANCE 21
Program to illustrate this keyword is used to refer current class
13-04-2021 INHERITANCE 22
 In a class hierarchy, when a method in a subclass has the same and
type signature as a method in its superclass, then the method in the
subclass is said to override the method in the superclass.
 When an overridden method is called from within a subclass, it will
always refer to the version of that method defined by the subclass.
 The version of the method defined by the superclass will be hidden.
 In object-oriented terms, overriding means to override the
functionality of an existing method.
 If subclass (child class) has the same method as declared in the
parent class, it is known as method overriding in Java.
Method Overriding
13-04-2021 INHERITANCE 23
13-04-2021 INHERITANCE 24
Usage of Java Method Overriding
 Method overriding is used to provide the specific
implementation of a method which is already provided by its
superclass.
 Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
 The method must have the same name as in the parent class
 The method must have the same parameter as in the parent
class.
 There must be an IS-A relationship (inheritance).
13-04-2021 INHERITANCE 25
13-04-2021 INHERITANCE 26
 final is a keyword in java used for restricting some
functionalities. We can declare variables, methods and classes
with final keyword.
 The keyword final has three uses.
1. Using final to create the equivalent of a named constant.
2. Using final to Prevent Overriding
3. Using final to prevent Inheritance
Using final with Inheritance
13-04-2021 INHERITANCE 27
final class A
{
// methods and fields
}
// The following class is illegal.
class B extends A {
// ERROR! Can't subclass A
}
Using final to Prevent Inheritance
13-04-2021 INHERITANCE 28
 Using final to Prevent Overriding
 When a method is declared as final then it cannot be overridden by
subclasses.
class A {
final void m1()
{
System.out.println("This is a final method.");
} }
class B extends A {
void m1()
{ // ERROR! Can't override.
System.out.println("Illegal!");
} }
13-04-2021 INHERITANCE 29
Types of Inheritance
13-04-2021 INHERITANCE 30
13-04-2021 INHERITANCE 31
Note: Multiple inheritance is not supported in Java through class.
When one class inherits multiple classes, it is known as
multiple inheritance.
For Example:
13-04-2021 INHERITANCE 32
Polygon
Rectangle
Triangle
IS – A relationship
Rectangle is a Polygon
Triangle is a Polygon Write a java program for the
above relationships?
13-04-2021 Introduction to Java and OO Concepts 33

More Related Content

What's hot

java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritance
Arjun Shanka
 
Object oriented basics
Object oriented basicsObject oriented basics
Object oriented basics
vamshimahi
 
8 abstract classes and interfaces
8   abstract classes and interfaces 8   abstract classes and interfaces
8 abstract classes and interfaces
Tuan Ngo
 
Oo abap-sap-1206973306636228-5
Oo abap-sap-1206973306636228-5Oo abap-sap-1206973306636228-5
Oo abap-sap-1206973306636228-5
prakash185645
 

What's hot (20)

java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritance
 
Simple java program
Simple java programSimple java program
Simple java program
 
Object oriented basics
Object oriented basicsObject oriented basics
Object oriented basics
 
Interfaces & Packages V2
Interfaces & Packages V2Interfaces & Packages V2
Interfaces & Packages V2
 
C#
C#C#
C#
 
C# interview questions
C# interview questionsC# interview questions
C# interview questions
 
Interfaces in JAVA !! why??
Interfaces in JAVA !!  why??Interfaces in JAVA !!  why??
Interfaces in JAVA !! why??
 
8 abstract classes and interfaces
8   abstract classes and interfaces 8   abstract classes and interfaces
8 abstract classes and interfaces
 
Abap Objects for BW
Abap Objects for BWAbap Objects for BW
Abap Objects for BW
 
Interfaces in java
Interfaces in javaInterfaces in java
Interfaces in java
 
Interface in java
Interface in javaInterface in java
Interface in java
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
Chapter 9 Interface
Chapter 9 InterfaceChapter 9 Interface
Chapter 9 Interface
 
Binding,interface,abstarct class
Binding,interface,abstarct classBinding,interface,abstarct class
Binding,interface,abstarct class
 
Micro Anti-patterns in Java Code
Micro Anti-patterns in Java CodeMicro Anti-patterns in Java Code
Micro Anti-patterns in Java Code
 
Java interface
Java interfaceJava interface
Java interface
 
C# interview quesions
C# interview quesionsC# interview quesions
C# interview quesions
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
Dynamic method dispatch
Dynamic method dispatchDynamic method dispatch
Dynamic method dispatch
 
Oo abap-sap-1206973306636228-5
Oo abap-sap-1206973306636228-5Oo abap-sap-1206973306636228-5
Oo abap-sap-1206973306636228-5
 

Similar to Chapter 3i

SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptxSodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
RudranilDas11
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
Tech_MX
 
Chapter 05 polymorphism extra
Chapter 05 polymorphism extraChapter 05 polymorphism extra
Chapter 05 polymorphism extra
Nurhanna Aziz
 
9781439035665 ppt ch10
9781439035665 ppt ch109781439035665 ppt ch10
9781439035665 ppt ch10
Terry Yoast
 
9781111530532 ppt ch10
9781111530532 ppt ch109781111530532 ppt ch10
9781111530532 ppt ch10
Terry Yoast
 

Similar to Chapter 3i (20)

Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptxSodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
 
Chapter 9 java
Chapter 9 javaChapter 9 java
Chapter 9 java
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
 
OCA Java SE 8 Exam Chapter 5 Class Design
OCA Java SE 8 Exam Chapter 5 Class DesignOCA Java SE 8 Exam Chapter 5 Class Design
OCA Java SE 8 Exam Chapter 5 Class Design
 
Java - Inheritance Concepts
Java - Inheritance ConceptsJava - Inheritance Concepts
Java - Inheritance Concepts
 
java_inheritance.pdf
java_inheritance.pdfjava_inheritance.pdf
java_inheritance.pdf
 
Core java by amit
Core java by amitCore java by amit
Core java by amit
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Chapter 05 polymorphism extra
Chapter 05 polymorphism extraChapter 05 polymorphism extra
Chapter 05 polymorphism extra
 
Inheritance ppt
Inheritance pptInheritance ppt
Inheritance ppt
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
 
Chap3 inheritance
Chap3 inheritanceChap3 inheritance
Chap3 inheritance
 
9781439035665 ppt ch10
9781439035665 ppt ch109781439035665 ppt ch10
9781439035665 ppt ch10
 
Lecture 12
Lecture 12Lecture 12
Lecture 12
 
116824015 java-j2 ee
116824015 java-j2 ee116824015 java-j2 ee
116824015 java-j2 ee
 
Dr. Rajeshree Khande : Java Inheritance
Dr. Rajeshree Khande : Java InheritanceDr. Rajeshree Khande : Java Inheritance
Dr. Rajeshree Khande : Java Inheritance
 
Lecture 10
Lecture 10Lecture 10
Lecture 10
 
9781111530532 ppt ch10
9781111530532 ppt ch109781111530532 ppt ch10
9781111530532 ppt ch10
 
Inheritance and its types In Java
Inheritance and its types In JavaInheritance and its types In Java
Inheritance and its types In Java
 

More from siragezeynu (12)

2 programming with c# i
2 programming with c# i2 programming with c# i
2 programming with c# i
 
6 database
6 database 6 database
6 database
 
Recovered file 1
Recovered file 1Recovered file 1
Recovered file 1
 
Chapter one
Chapter oneChapter one
Chapter one
 
Chapter 4
Chapter 4Chapter 4
Chapter 4
 
Chapter 3
Chapter 3Chapter 3
Chapter 3
 
Chapter 5
Chapter 5Chapter 5
Chapter 5
 
Lab4
Lab4Lab4
Lab4
 
Chapter 6
Chapter 6Chapter 6
Chapter 6
 
Chapter 1
Chapter 1Chapter 1
Chapter 1
 
Chapter 2
Chapter 2Chapter 2
Chapter 2
 
6 chapter 6 record storage and primary file organization
6 chapter 6  record storage and primary file organization6 chapter 6  record storage and primary file organization
6 chapter 6 record storage and primary file organization
 

Recently uploaded

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 

Recently uploaded (20)

Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 

Chapter 3i

  • 1. CHAPTER 3 INHERITANCE By Sirage Zeynu (M.Tech) School of Computing
  • 2. 13-04-2021 INHERITANCE 2 Outline of this chapter 1.Concept of inheritance 2.Super classes and subclasses 3.Protected members 4.Overriding methods 5.Using this () and super () 6.Use of final with inheritance 7.Constructors in subclasses
  • 3. 13-04-2021 INHERITANCE 3 What is Inheritance ? Inheritance is one of the cornerstones of object-oriented programming because it allows the creation of hierarchical classifications. In Java, classes can be derived from classes. Basically, if you need to create a new class and here is already a class that has some of the code you require, then it is possible to derive your new class from the already existing code. This concept allows you to reuse the fields and methods of the existing class without having to rewrite the code in a new class. In this scenario, the existing class is called the superclass and the derived class is called the subclass. To inherit a class, you simply incorporate the definition of one class into another by using the extends keyword.
  • 4. 13-04-2021 INHERITANCE 4 Inheritance is one such concept where the properties of one class can be inherited by the other. It helps to reuse the code and establish a relationship between different classes. extends Keyword extends is the keyword used to inherit the properties of a class. Following is the syntax of extends keyword. class Super{ ..... ..... } class Sub extends Super { ..... ..... }
  • 5. 13-04-2021 INHERITANCE 5 A simple example of inheritance
  • 7. 13-04-2021 INHERITANCE 7  Inheritance relationships form tree-like hierarchical structures.  A superclass exists in a hierarchical relationship with its subclasses.  When classes participate in inheritance relationships, they become “affiliated” with other classes.  A class becomes either a superclass, supplying members to other classes, or a subclass, inheriting its members from other classes  note that super classes tend to be “more general” and subclasses “more specific.” Super classes and Subclasses
  • 8. 13-04-2021 INHERITANCE 8 Super class (base/parent/driver/inheritance/ ancestor class). Intermediate class (mediating/dual class). Child class (sub/associate/derived/inherited class).
  • 9. 13-04-2021 INHERITANCE 9  A superclass’s public members are accessible anywhere the program has a reference to that superclass type or one of its subclass types.  A superclass’s private members are accessible only in methods of that superclass.  A superclass’s protected members may be accessed only by methods of the superclass, by methods of subclasses and by methods of other classes in the same package (protected members have package access).  Subclass methods can normally refer to public and protected members of the superclass simply by using the member names. Member Access and Inheritance
  • 10. 13-04-2021 INHERITANCE 10 class Access { public static void main ( String args[ ] ) { B subob = new B ( ); subob.setij (10, 12 ); subob.sum( ); System.out.println ( “ Total is “ + subob.total ); }} class A { int i; // public by default private int j; // private to A void setij ( int x, int y) { i = x; j = y; }} // A’s j is not accessible here class B extends A { int total ; void sum ( ) { total =i + j ; // Error, j is not accessible here }} / * In a class hierarchy, private members remain private to their class. This program contains an error and will not compile */
  • 11. 13-04-2021 INHERITANCE 11  The super keyword is similar to this keyword. Following are the scenarios where the super keyword is used.  It is used to differentiate the members of super class from the members of sub class, if they have same names.  It is used to invoke the super class constructor from subclass.  If a class is inheriting the properties of another class. And if the members of the superclass have the names same as the sub class, to differentiate these variables we use super keyword. The super keyword
  • 14. 13-04-2021 INHERITANCE 14 Output of the above program
  • 15. 13-04-2021 INHERITANCE 15  A subclass can call a constructor method defined by its superclass by use of the following form of super. super ( parameter-list );  Here, parameter-list specifies any parameters needed by the constructor in the superclass.  super ( ) must always be the first statement executer inside a subclass constructor. Using super to call superclass Constructor
  • 17. 13-04-2021 INHERITANCE 17  The first thing a subclass constructor must do is call the superclass constructor  This ensures that the superclass part of the object is constructed before the subclass part  If you do not call the superclass constructor with the super keyword, and the superclass has a constructor with no arguments, then that superclass constructor will be called implicitly. Subclass Constructor
  • 18. Implicit Super Constructor Call If I have this Food class: public class Food { private boolean raw; public Food() { raw = true; } } then this Beef subclass: public class Beef extends Food { private double weight; public Beef(double w) { weight = w }} is equivalent to: public class Beef extends Food { private double weight; public Beef(double w) { super(); weight = w } }
  • 19. 13-04-2021 INHERITANCE 19 The this keyword  A special reference value called this is included in Java .  The this keyword is used inside any instance method to refer to the current object .  The value this refers to the object which the current method has been called on .  The this keyword can be used where a reference to an object of the current class type is required .
  • 20. 13-04-2021 INHERITANCE 20 The following example illustrates the usage of the keyword this. The output appear as given below :
  • 21. 13-04-2021 INHERITANCE 21 Program to illustrate this keyword is used to refer current class
  • 22. 13-04-2021 INHERITANCE 22  In a class hierarchy, when a method in a subclass has the same and type signature as a method in its superclass, then the method in the subclass is said to override the method in the superclass.  When an overridden method is called from within a subclass, it will always refer to the version of that method defined by the subclass.  The version of the method defined by the superclass will be hidden.  In object-oriented terms, overriding means to override the functionality of an existing method.  If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in Java. Method Overriding
  • 24. 13-04-2021 INHERITANCE 24 Usage of Java Method Overriding  Method overriding is used to provide the specific implementation of a method which is already provided by its superclass.  Method overriding is used for runtime polymorphism Rules for Java Method Overriding  The method must have the same name as in the parent class  The method must have the same parameter as in the parent class.  There must be an IS-A relationship (inheritance).
  • 26. 13-04-2021 INHERITANCE 26  final is a keyword in java used for restricting some functionalities. We can declare variables, methods and classes with final keyword.  The keyword final has three uses. 1. Using final to create the equivalent of a named constant. 2. Using final to Prevent Overriding 3. Using final to prevent Inheritance Using final with Inheritance
  • 27. 13-04-2021 INHERITANCE 27 final class A { // methods and fields } // The following class is illegal. class B extends A { // ERROR! Can't subclass A } Using final to Prevent Inheritance
  • 28. 13-04-2021 INHERITANCE 28  Using final to Prevent Overriding  When a method is declared as final then it cannot be overridden by subclasses. class A { final void m1() { System.out.println("This is a final method."); } } class B extends A { void m1() { // ERROR! Can't override. System.out.println("Illegal!"); } }
  • 31. 13-04-2021 INHERITANCE 31 Note: Multiple inheritance is not supported in Java through class. When one class inherits multiple classes, it is known as multiple inheritance. For Example:
  • 32. 13-04-2021 INHERITANCE 32 Polygon Rectangle Triangle IS – A relationship Rectangle is a Polygon Triangle is a Polygon Write a java program for the above relationships?
  • 33. 13-04-2021 Introduction to Java and OO Concepts 33

Editor's Notes

  1. Inheritance is one of the cornerstones of object-oriented programming because it allows the creation of hierarchical classifications. Using inheritance, you can create a general class that defines traits 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 the terminology of Java, a class that is inherited is called a superclass. The class that does the inheriting is called a subclass. Therefore, a subclass is a specialized version of a superclass and adds its own, unique elements. In Java, classes can be derived from classes. Basically, if you need to create a new class and here is already a class that has some of the code you require, then it is possible to derive your new class from the already existing code. This concept allows you to reuse the fields and methods of the existing class without having to rewrite the code in a new class. In this scenario, the existing class is called the superclass and the derived class is called the subclass.
  2. Often, an object of one class is an object of another class as well. For example, in geometry, a rectangle is a quadrilateral (as are squares, parallelograms and trapezoids). Thus, in Java, class Rectangle can be said to inherit from class Quadrilateral. In this context, class Quadrilateral is a superclass and class Rectangle is a subclass. A rectangle is a specific type of quadrilateral, but it is incorrect to claim that every quadrilateral is a rectangle—the quadrilateral could be a parallelogram or some other shape. Figure 9.1 lists several simple examples of superclasses and subclasses—note that superclasses tend to be “more general” and subclasses “more specific.” Because every subclass object is an object of its superclass, and one superclass can have many subclasses, the set of objects represented by a superclass is typically larger than the set of objects represented by any of its subclasses. For example, the superclass Vehicle rep- resents all vehicles, including cars, trucks, boats, bicycles and so on. By contrast, subclass Car represents a smaller, more specific subset of vehicles. Inheritance relationships form tree-like hierarchical structures. A superclass exists in a hierarchical relationship with its subclasses. When classes participate in inheritance rela- tionships, they become “affiliated” with other classes. A class becomes either a superclass, supplying members to other classes, or a subclass, inheriting its members from other classes. In some cases, a class is both a superclass and a subclass.
  3. Although a subclass includes all of the members of its superclass, it cannot access those members of the superclass that have been declared as private . A superclass’s public members are accessible anywhere the program has a reference to that superclass type or one of its subclass types. A superclass’s private members are accessible only in methods of that superclass. A superclass’s protected access members serve as an intermediate level of protection between public and private access. A superclass’s protected members may be accessed only by methods of the superclass, by methods of subclasses and by methods of other classes in the same package (protected members have package access). Subclass methods can normally refer to public and protected members of the superclass simply by using the member names. When a subclass method overrides a superclass method, the superclass method may be accessed from the subclass by preceding the superclass method name with keyword super followed by the dot operator (.). This technique is illustrated latter.  
  4. super has two general forms. The first calls the superclass constructor . The second is used to access a member of the superclass that has been hidden by a member of a subclass.
  5. This section provides you a program that demonstrates the usage of the super keyword. In the given program, you have two classes namely Sub_class and Super_class, both have a method named display() with different implementations, and a variable named num with different values. We are invoking display() method of both classes and printing the value of the variable num of both classes. Here you can observe that we have used super keyword to differentiate the members of superclass from subclass. Copy and paste the program in a file with name Sub_class.java.
  6. This section provides you a program that demonstrates the usage of the super keyword. In the given program, you have two classes namely Sub_class and Super_class, both have a method named display() with different implementations, and a variable named num with different values. We are invoking display() method of both classes and printing the value of the variable num of both classes. Here you can observe that we have used super keyword to differentiate the members of superclass from subclass. Copy and paste the program in a file with name Sub_class.java.
  7. If a class is inheriting the properties of another class, the subclass automatically acquires the default constructor of the superclass. But if you want to call a parameterized constructor of the superclass, you need to use the super keyword as shown below. super(values); Sample Code The program given in this section demonstrates how to use the super keyword to invoke the parametrized constructor of the superclass. This program contains a superclass and a subclass, where the superclass contains a parameterized constructor which accepts a integer value, and we used the super keyword to invoke the parameterized constructor of the superclass. Copy and paste the following program in a file with the name Subclass.java
  8. Using the this Keyword Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this. Using this with a Field The most common reason for using the this keyword is because a field is shadowed by a method or constructor parameter. For example, the Point class was written like this public class Point { public int x = 0; public int y = 0; //constructor public Point(int a, int b) { x = a; y = b; } } but it could have been written like this: public class Point { public int x = 0; public int y = 0; //constructor public Point(int x, int y) { this.x = x; this.y = y; } } Each argument to the constructor shadows one of the object's fields — inside the constructor x is a local copy of the constructor's first argument. To refer to the Point field x, the constructor must use this.x. Using this with a Constructor From within a constructor, you can also use the this keyword to call another constructor in the same class. Doing so is called an explicit constructor invocation. Here's another Rectangle class, with a different implementation from the one in the Objects section. public class Rectangle { private int x, y; private int width, height; public Rectangle() { this(0, 0, 1, 1); } public Rectangle(int width, int height) { this(0, 0, width, height); } public Rectangle(int x, int y, int width, int height) { this.x = x; this.y = y; this.width = width; this.height = height; } } This class contains a set of constructors. Each constructor initializes some or all of the rectangle's member variables. The constructors provide a default value for any member variable whose initial value is not provided by an argument. For example, the no-argument constructor creates a 1x1 Rectangle at coordinates 0,0. The two-argument constructor calls the four-argument constructor, passing in the width and height but always using the 0,0 coordinates. As before, the compiler determines which constructor to call, based on the number and the type of arguments.
  9. Output Animals can move Dogs can walk and run In the above example, you can see that even though b is a type of Animal it runs the move method in the Dog class. The reason for this is: In compile time, the check is made on the reference type. However, in the runtime, JVM figures out the object type and would run the method that belongs to that particular object. Therefore, in the above example, the program will compile properly since Animal class has the method move. Then, at the runtime, it runs the method specific for that object.
  10. Using final to Prevent Inheritance When a class is declared as final then it cannot be subclassed i.e. no any other class can extend it. This is particularly useful, for example, when creating an immutable class like the predefined String class. The following fragment illustrates final keyword with a class: Declaring a class as final implicitly declares all of its methods as final, too. It is illegal to declare a class as both abstract and final since an abstract class is incomplete by itself and relies upon its subclasses to provide complete implementations. For more on abstract classes, refer abstract classes in java
  11. Using final to Prevent Overriding When a method is declared as final then it cannot be overridden by subclasses.The Object class does this—a number of its methods are final. The following fragment illustrates final keyword with a method:
  12. Why multiple inheritance is not supported in java? To reduce the complexity and simplify the language, multiple inheritance is not supported in java. Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A and B classes have the same method and you call it from child class object, there will be ambiguity to call the method of A or B class. Since compile-time errors are better than runtime errors, Java renders compile-time error if you inherit 2 classes. So whether you have same method or different, there will be compile time error.
  13. IS-A is a way of saying: This object is a type of that object. Let us see how the extends keyword is used to achieve inheritance. public class Animal { } public class Mammal extends Animal { } public class Reptile extends Animal { } public class Dog extends Mammal { }Now, based on the above example, in Object-Oriented terms, the following are true − Animal is the superclass of Mammal class. Animal is the superclass of Reptile class. Mammal and Reptile are subclasses of Animal class. Dog is the subclass of both Mammal and Animal classes. Now, if we consider the IS-A relationship, we can say − Mammal IS-A Animal Reptile IS-A Animal Dog IS-A Mammal Hence: Dog IS-A Animal as well