SlideShare a Scribd company logo
Unit-5
Inheritance, Super& Sub Class
Satya Ram Suwal
Asst.Lecturer
NOU
Inheritance
• Inheritance can be defined as the process where one
class acquires the properties (methods and fields) of
another. With the use of inheritance the information is
made manageable in a hierarchical order.
• The class which inherits the properties of other is known
as subclass (derived class, child class) and the class
whose properties are inherited is known as superclass
(base class, parent class).
extends Keyword
extends is the keyword used to inherit the
properties of a class. Following is the syntax
of extends keyword.
Syntax
class Super
{ ..... ..... }
class Sub extends Super
{ ..... ..... }
class Calculation {
int z;
public void addition(int x, int y)
{
z = x + y;
System.out.println("The sum of the given numbers:"+z);
}
public void Subtraction(int x, int y)
{
z = x - y;
System.out.println("The difference between the given
numbers:"+z);
}
}
public class My_Calculation extends Calculation {
public void multiplication(int x, int y)
{
z = x * y;
System.out.println("The product of the given numbers:"+z);
}
public static void main(String args[])
{ int a = 20, b = 10;
My_Calculation demo = new My_Calculation();
demo.addition(a, b);
demo.Subtraction(a, b);
demo.multiplication(a, b);
}
Important terminology:
• Super Class: The class whose features are inherited is
known as super class(or a base class or a parent class).
• Sub Class: The class that inherits the other class is
known as sub class(or a derived class, extended class,
or child class). The subclass can add its own fields and
methods in addition to the superclass fields and
methods.
• Reusability: Inheritance supports the concept of
“reusability”, i.e. when we want to create a new class
and there is already a class that includes some of the
code that we want, we can derive our new class from the
existing class. By doing this, we are reusing the fields
and methods of the existing class.
//Java program to illustrate the
// concept of inheritance
// base class
class Bicycle
{
// the Bicycle class has two fields
public int gear;
public int speed;
// the Bicycle class has one constructor
public Bicycle(int gear, int speed)
{
this.gear = gear;
this.speed = speed;
}
// the Bicycle class has three methods
public void applyBrake(int decrement)
{
speed -= decrement;
}
public void speedUp(int increment)
{
speed += increment;
}
// toString() method to print info of Bicycle
public String toString()
{
return("No of gears are "+gear +"n“
+ "speed of bicycle is "+speed);
}
}
// derived class
class MountainBike extends Bicycle
{
// the MountainBike subclass adds one more field
public int seatHeight;
// the MountainBike subclass has one constructor
public MountainBike(int gear,int speed, int startHeight)
{
// invoking base-class(Bicycle) constructor
super(gear, speed);
seatHeight = startHeight;
}
// the MountainBike subclass adds one more method
public void setHeight(int newValue)
{
seatHeight = newValue;
}
// overriding toString() method
// of Bicycle to print more info
@Override
public String toString()
{
return (super.toString()+ "nseat height is "+seatHeight);
}
}
// driver class
public class Test
{
public static void main(String args[])
{
MountainBike mb = new MountainBike(3, 100, 25);
System.out.println(mb.toString());
In above program, when an object of MountainBike class is created, a copy of the all methods
and fields of the superclass acquire memory in this object. That is why, by using the object of
the subclass we can also access the members of a superclass.
Please note that during inheritance only object of subclass is created, not the superclass
Illustrative image of the program:
Java and Multiple Inheritance
• Multiple Inheritance is a feature of object oriented
concept, where a class can inherit properties of more
than one parent class. The problem occurs when there
exist methods with same signature in both the super
classes and subclass. On calling the method, the
compiler cannot determine which class method to be
called and even on calling which class method gets the
priority.
• // First Parent class
• class Parent1
• {
• void fun()
• {
• System.out.println("Parent1");
• }
• }
• // Second Parent Class
• class Parent2
• {
• void fun()
• {
• System.out.println("Parent2");
• }
• }
• // Error : Test is inheriting from multiple
• // classes
• class Test extends Parent1, Parent2
• {
• public static void main(String args[])
• {
• Test t = new Test();
• t.fun();
• }
• }
The super keyword
• 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 superclass
from the members of subclass, if they have same
names.
• It is used to invoke the superclass constructor from
subclass.
class Super_class {
int num = 20; // display method of superclass
public void display() {
System.out.println("This is the display method of superclass");
} }
public class Sub_class extends Super_class {
int num = 10; // display method of sub class
public void display() {
System.out.println("This is the display method of subclass");
}
public void my_method() {
// Instantiating subclass
Sub_class sub = new Sub_class(); // Invoking the display() method
of sub class
sub.display(); // Invoking the display() method of superclass
super.display(); // printing the value of variable num of subclass
System.out.println("value of the variable named num in sub class:"+
sub.num); // printing the value of variable num of superclass
System.out.println("value of the variable named num in super
class:"+ super.num);
}
public static void main(String args[])
{ Sub_class obj = new Sub_class();
obj.my_method();
} }
Multilevel Inheritance Example
• When there is a chain of inheritance, it is known
as multilevel inheritance. As you can see in the
example given below, BabyDog class inherits the
Dog class which again inherits the Animal class,
so there is a multilevel inheritance.
1. class Animal{
2. void eat(){
3. System.out.println("eating...");
4. }
5. }
6. class Dog extends Animal{
7. void bark(){
8. System.out.println("barking
9.
10.}
11.class BabyDog extends Dog{
12.void weep(){System.out.println("weeping...");}
13.}
14.class TestInheritance2{
15.public static void main(String args[]){
16.BabyDog d=new BabyDog();
17.d.weep();
18.d.bark();
19.d.eat();
20.}}
Hierarchical Inheritance Example
• When two or more classes inherits a single class, it is known as hierarchical inheritance. In the
example given below, Dog and Cat classes inherits the Animal class, so there is hierarchical
inheritance.
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class Cat extends Animal{
8. void meow(){System.out.println("meowing...");}
9. }
10.class TestInheritance3{
11.public static void main(String args[]){
12. Cat c=new Cat();
13. c.meow();
14. c.eat();
15. //c.bark();//C.T.Error
16. }}
There are various types of inheritance as demonstrated below.
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.
1. class A{
2. void msg(){System.out.println("Hello");}
3. }
4. class B{
5. void msg(){System.out.println("Welcome");}
6. }
7. class C extends A,B{//suppose if it were
8.
9. public static void main(String args[]){
10. C obj=new C();
11. obj.msg();//Now which msg() method would be invoked?
12.}
13.}
Nested Classes
• In Java, just like methods, variables of a class too can
have another class as its member. Writing a class within
another is allowed in Java. The class written within is
called the nested class, and the class that holds the
inner class is called the outer class.
• Syntax
• Following is the syntax to write a nested class. Here, the
class Outer_Demo is the outer class and the
class Inner_Demo is the nested class.
class Outer_Demo {
class Inner_Demo
{
}
}
Nested classes are divided into two types −
•Non-static nested classes − These are the non-static members of a class.
•Static nested classes − These are the static members of a class.
Inner Classes (Non-static Nested Classes)
• Inner classes are a security mechanism in Java. We
know a class cannot be associated with the access
modifier private, but if we have the class as a member
of other class, then the inner class can be made private.
And this is also used to access the private members of a
class.
• Inner classes are of three types depending on how and
where you define them. They are −
• Inner Class
• Method-local Inner Class
• Anonymous Inner Class
class Outer_Demo {
int num; // inner class private class
Inner_Demo {
public void print() { System.out.println("This is an
inner class");
} }
// Accessing he inner class from the method within
void display_Inner()
{ Inner_Demo inner = new Inner_Demo();
inner.print();
} }
public class My_class {
public static void main(String args[])
{ // Instantiating the outer class
Outer_Demo outer = new Outer_Demo();
// Accessing the display_Inner() method.
outer.display_Inner();
} }
Accessing the Private Members
class Outer_Demo
{
// private variable of the outer class
private int num = 175; // inner class
public class Inner_Demo
{
public int getNum() {
System.out.println("This is the getnum method of the inner class");
return num;
}
} }
public class My_class2 {
public static void main(String args[]) {
// Instantiating the outer class
Outer_Demo outer = new Outer_Demo();
// Instantiating the inner class
Outer_Demo.Inner_Demo inner = outer.new Inner_Demo();
System.out.println(inner.getNum());
Method-local Inner Class
• In Java, we can write a class within a method and this
will be a local type. Like local variables, the scope of the
inner class is restricted within the method.
1. public class localInner1{
2. private int data=30;//instance variable
3. void display(){
4. class Local{
5. void msg(){System.out.println(data);}
6. }
7. Local l=new Local();
8. l.msg();
9. }
10. public static void main(String args[]){
11. localInner1 obj=new localInner1();
12. obj.display();
13. }
14.}
Java Anonymous inner class
• A class that have no name is known as
anonymous inner class in java. It should be used
if you have to override method of class or
interface. Java Anonymous inner class can be
created by two ways:
1.Class (may be abstract or concrete).
2.Interface
Java anonymous inner class example
1.abstract class Person{
2. abstract void eat();
3.}
4.class TestAnonymousInner{
5. public static void main(String args[]){
6. Person p=new Person(){
7. void eat(){System.out.println("nice fruits");}
8. };
9. p.eat();
10. }
11.}
Ananymous inner Class Example
class Demo {
void show() {
System.out.println("i am in show method of super class");
}
}
class Flavor1Demo {
// An anonymous class with Demo as base class
static Demo d = new Demo() {
void show() {
super.show();
System.out.println("i am in Flavor1Demo class");
}
};
public static void main(String[] args){
d.show();
}
}
References
• www.javatpoint.com

More Related Content

Similar to UNIT 5.pptx

Chap-3 Inheritance.pptx
Chap-3 Inheritance.pptxChap-3 Inheritance.pptx
Chap-3 Inheritance.pptx
chetanpatilcp783
 
INHERITANCE IN JAVA.pptx
INHERITANCE IN JAVA.pptxINHERITANCE IN JAVA.pptx
INHERITANCE IN JAVA.pptx
NITHISG1
 
Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1
PRN USM
 
Java Inheritance
Java InheritanceJava Inheritance
Java Inheritance
Manish Tiwari
 
Object oriented concepts
Object oriented conceptsObject oriented concepts
Object oriented concepts
Gousalya Ramachandran
 
Corejava Training in Bangalore Tutorial
Corejava Training in Bangalore TutorialCorejava Training in Bangalore Tutorial
Corejava Training in Bangalore Tutorial
rajkamaltibacademy
 
Chapter 5 (OOP Principles).ppt
Chapter 5 (OOP Principles).pptChapter 5 (OOP Principles).ppt
Chapter 5 (OOP Principles).ppt
henokmetaferia1
 
Core java oop
Core java oopCore java oop
Core java oop
Parth Shah
 
Day_2.1.pptx
Day_2.1.pptxDay_2.1.pptx
Day_2.1.pptx
ishasharma835109
 
Java Inheritance
Java InheritanceJava Inheritance
Java Inheritance
Rosie Jane Enomar
 
inheritance
inheritanceinheritance
inheritance
Jay Prajapati
 
L7 inheritance
L7 inheritanceL7 inheritance
L7 inheritance
teach4uin
 
L7 inheritance
L7 inheritanceL7 inheritance
L7 inheritance
teach4uin
 
encapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingencapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloading
Shivam Singhal
 
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
 
Java Reflection
Java ReflectionJava Reflection
Java Reflection
Hamid Ghorbani
 
Inheritance chepter 7
Inheritance chepter 7Inheritance chepter 7
Inheritance chepter 7
kamal kotecha
 
Inheritance
InheritanceInheritance
Inheritance
Munsif Ullah
 
Java for the Impatient, Java Constructors, Scope, Wrappers, Inheritance, and ...
Java for the Impatient, Java Constructors, Scope, Wrappers, Inheritance, and ...Java for the Impatient, Java Constructors, Scope, Wrappers, Inheritance, and ...
Java for the Impatient, Java Constructors, Scope, Wrappers, Inheritance, and ...
argsstring
 

Similar to UNIT 5.pptx (20)

Chap-3 Inheritance.pptx
Chap-3 Inheritance.pptxChap-3 Inheritance.pptx
Chap-3 Inheritance.pptx
 
INHERITANCE IN JAVA.pptx
INHERITANCE IN JAVA.pptxINHERITANCE IN JAVA.pptx
INHERITANCE IN JAVA.pptx
 
Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1
 
Java Inheritance
Java InheritanceJava Inheritance
Java Inheritance
 
Object oriented concepts
Object oriented conceptsObject oriented concepts
Object oriented concepts
 
Corejava Training in Bangalore Tutorial
Corejava Training in Bangalore TutorialCorejava Training in Bangalore Tutorial
Corejava Training in Bangalore Tutorial
 
Chapter 5 (OOP Principles).ppt
Chapter 5 (OOP Principles).pptChapter 5 (OOP Principles).ppt
Chapter 5 (OOP Principles).ppt
 
Core java oop
Core java oopCore java oop
Core java oop
 
Day_2.1.pptx
Day_2.1.pptxDay_2.1.pptx
Day_2.1.pptx
 
Java Inheritance
Java InheritanceJava Inheritance
Java Inheritance
 
inheritance
inheritanceinheritance
inheritance
 
L7 inheritance
L7 inheritanceL7 inheritance
L7 inheritance
 
L7 inheritance
L7 inheritanceL7 inheritance
L7 inheritance
 
encapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingencapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloading
 
Presentation 3.pdf
Presentation 3.pdfPresentation 3.pdf
Presentation 3.pdf
 
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
 
Java Reflection
Java ReflectionJava Reflection
Java Reflection
 
Inheritance chepter 7
Inheritance chepter 7Inheritance chepter 7
Inheritance chepter 7
 
Inheritance
InheritanceInheritance
Inheritance
 
Java for the Impatient, Java Constructors, Scope, Wrappers, Inheritance, and ...
Java for the Impatient, Java Constructors, Scope, Wrappers, Inheritance, and ...Java for the Impatient, Java Constructors, Scope, Wrappers, Inheritance, and ...
Java for the Impatient, Java Constructors, Scope, Wrappers, Inheritance, and ...
 

Recently uploaded

When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
UiPathCommunity
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
RinaMondal9
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
Peter Spielvogel
 

Recently uploaded (20)

When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
 

UNIT 5.pptx

  • 1. Unit-5 Inheritance, Super& Sub Class Satya Ram Suwal Asst.Lecturer NOU
  • 2. Inheritance • Inheritance can be defined as the process where one class acquires the properties (methods and fields) of another. With the use of inheritance the information is made manageable in a hierarchical order. • The class which inherits the properties of other is known as subclass (derived class, child class) and the class whose properties are inherited is known as superclass (base class, parent class).
  • 3. extends Keyword extends is the keyword used to inherit the properties of a class. Following is the syntax of extends keyword. Syntax class Super { ..... ..... } class Sub extends Super { ..... ..... }
  • 4. class Calculation { int z; public void addition(int x, int y) { z = x + y; System.out.println("The sum of the given numbers:"+z); } public void Subtraction(int x, int y) { z = x - y; System.out.println("The difference between the given numbers:"+z); } } public class My_Calculation extends Calculation { public void multiplication(int x, int y) { z = x * y; System.out.println("The product of the given numbers:"+z); } public static void main(String args[]) { int a = 20, b = 10; My_Calculation demo = new My_Calculation(); demo.addition(a, b); demo.Subtraction(a, b); demo.multiplication(a, b); }
  • 5. Important terminology: • Super Class: The class whose features are inherited is known as super class(or a base class or a parent class). • Sub Class: The class that inherits the other class is known as sub class(or a derived class, extended class, or child class). The subclass can add its own fields and methods in addition to the superclass fields and methods. • Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and there is already a class that includes some of the code that we want, we can derive our new class from the existing class. By doing this, we are reusing the fields and methods of the existing class.
  • 6. //Java program to illustrate the // concept of inheritance // base class class Bicycle { // the Bicycle class has two fields public int gear; public int speed; // the Bicycle class has one constructor public Bicycle(int gear, int speed) { this.gear = gear; this.speed = speed; } // the Bicycle class has three methods public void applyBrake(int decrement) { speed -= decrement; } public void speedUp(int increment) { speed += increment; } // toString() method to print info of Bicycle public String toString() { return("No of gears are "+gear +"n“ + "speed of bicycle is "+speed); } } // derived class class MountainBike extends Bicycle { // the MountainBike subclass adds one more field public int seatHeight; // the MountainBike subclass has one constructor public MountainBike(int gear,int speed, int startHeight) { // invoking base-class(Bicycle) constructor super(gear, speed); seatHeight = startHeight; } // the MountainBike subclass adds one more method public void setHeight(int newValue) { seatHeight = newValue; } // overriding toString() method // of Bicycle to print more info @Override public String toString() { return (super.toString()+ "nseat height is "+seatHeight); } } // driver class public class Test { public static void main(String args[]) { MountainBike mb = new MountainBike(3, 100, 25); System.out.println(mb.toString());
  • 7. In above program, when an object of MountainBike class is created, a copy of the all methods and fields of the superclass acquire memory in this object. That is why, by using the object of the subclass we can also access the members of a superclass. Please note that during inheritance only object of subclass is created, not the superclass Illustrative image of the program:
  • 8. Java and Multiple Inheritance • Multiple Inheritance is a feature of object oriented concept, where a class can inherit properties of more than one parent class. The problem occurs when there exist methods with same signature in both the super classes and subclass. On calling the method, the compiler cannot determine which class method to be called and even on calling which class method gets the priority.
  • 9. • // First Parent class • class Parent1 • { • void fun() • { • System.out.println("Parent1"); • } • } • // Second Parent Class • class Parent2 • { • void fun() • { • System.out.println("Parent2"); • } • } • // Error : Test is inheriting from multiple • // classes • class Test extends Parent1, Parent2 • { • public static void main(String args[]) • { • Test t = new Test(); • t.fun(); • } • }
  • 10. The super keyword • 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 superclass from the members of subclass, if they have same names. • It is used to invoke the superclass constructor from subclass.
  • 11. class Super_class { int num = 20; // display method of superclass public void display() { System.out.println("This is the display method of superclass"); } } public class Sub_class extends Super_class { int num = 10; // display method of sub class public void display() { System.out.println("This is the display method of subclass"); } public void my_method() { // Instantiating subclass Sub_class sub = new Sub_class(); // Invoking the display() method of sub class sub.display(); // Invoking the display() method of superclass super.display(); // printing the value of variable num of subclass System.out.println("value of the variable named num in sub class:"+ sub.num); // printing the value of variable num of superclass System.out.println("value of the variable named num in super class:"+ super.num); } public static void main(String args[]) { Sub_class obj = new Sub_class(); obj.my_method(); } }
  • 12. Multilevel Inheritance Example • When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the example given below, BabyDog class inherits the Dog class which again inherits the Animal class, so there is a multilevel inheritance.
  • 13. 1. class Animal{ 2. void eat(){ 3. System.out.println("eating..."); 4. } 5. } 6. class Dog extends Animal{ 7. void bark(){ 8. System.out.println("barking 9. 10.} 11.class BabyDog extends Dog{ 12.void weep(){System.out.println("weeping...");} 13.} 14.class TestInheritance2{ 15.public static void main(String args[]){ 16.BabyDog d=new BabyDog(); 17.d.weep(); 18.d.bark(); 19.d.eat(); 20.}}
  • 14. Hierarchical Inheritance Example • When two or more classes inherits a single class, it is known as hierarchical inheritance. In the example given below, Dog and Cat classes inherits the Animal class, so there is hierarchical inheritance. 1. class Animal{ 2. void eat(){System.out.println("eating...");} 3. } 4. class Dog extends Animal{ 5. void bark(){System.out.println("barking...");} 6. } 7. class Cat extends Animal{ 8. void meow(){System.out.println("meowing...");} 9. } 10.class TestInheritance3{ 11.public static void main(String args[]){ 12. Cat c=new Cat(); 13. c.meow(); 14. c.eat(); 15. //c.bark();//C.T.Error 16. }}
  • 15. There are various types of inheritance as demonstrated below.
  • 16. 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.
  • 17. 1. class A{ 2. void msg(){System.out.println("Hello");} 3. } 4. class B{ 5. void msg(){System.out.println("Welcome");} 6. } 7. class C extends A,B{//suppose if it were 8. 9. public static void main(String args[]){ 10. C obj=new C(); 11. obj.msg();//Now which msg() method would be invoked? 12.} 13.}
  • 18. Nested Classes • In Java, just like methods, variables of a class too can have another class as its member. Writing a class within another is allowed in Java. The class written within is called the nested class, and the class that holds the inner class is called the outer class. • Syntax • Following is the syntax to write a nested class. Here, the class Outer_Demo is the outer class and the class Inner_Demo is the nested class. class Outer_Demo { class Inner_Demo { } }
  • 19. Nested classes are divided into two types − •Non-static nested classes − These are the non-static members of a class. •Static nested classes − These are the static members of a class.
  • 20. Inner Classes (Non-static Nested Classes) • Inner classes are a security mechanism in Java. We know a class cannot be associated with the access modifier private, but if we have the class as a member of other class, then the inner class can be made private. And this is also used to access the private members of a class. • Inner classes are of three types depending on how and where you define them. They are − • Inner Class • Method-local Inner Class • Anonymous Inner Class
  • 21. class Outer_Demo { int num; // inner class private class Inner_Demo { public void print() { System.out.println("This is an inner class"); } } // Accessing he inner class from the method within void display_Inner() { Inner_Demo inner = new Inner_Demo(); inner.print(); } } public class My_class { public static void main(String args[]) { // Instantiating the outer class Outer_Demo outer = new Outer_Demo(); // Accessing the display_Inner() method. outer.display_Inner(); } }
  • 22. Accessing the Private Members class Outer_Demo { // private variable of the outer class private int num = 175; // inner class public class Inner_Demo { public int getNum() { System.out.println("This is the getnum method of the inner class"); return num; } } } public class My_class2 { public static void main(String args[]) { // Instantiating the outer class Outer_Demo outer = new Outer_Demo(); // Instantiating the inner class Outer_Demo.Inner_Demo inner = outer.new Inner_Demo(); System.out.println(inner.getNum());
  • 23. Method-local Inner Class • In Java, we can write a class within a method and this will be a local type. Like local variables, the scope of the inner class is restricted within the method. 1. public class localInner1{ 2. private int data=30;//instance variable 3. void display(){ 4. class Local{ 5. void msg(){System.out.println(data);} 6. } 7. Local l=new Local(); 8. l.msg(); 9. } 10. public static void main(String args[]){ 11. localInner1 obj=new localInner1(); 12. obj.display(); 13. } 14.}
  • 24. Java Anonymous inner class • A class that have no name is known as anonymous inner class in java. It should be used if you have to override method of class or interface. Java Anonymous inner class can be created by two ways: 1.Class (may be abstract or concrete). 2.Interface
  • 25. Java anonymous inner class example 1.abstract class Person{ 2. abstract void eat(); 3.} 4.class TestAnonymousInner{ 5. public static void main(String args[]){ 6. Person p=new Person(){ 7. void eat(){System.out.println("nice fruits");} 8. }; 9. p.eat(); 10. } 11.}
  • 26. Ananymous inner Class Example class Demo { void show() { System.out.println("i am in show method of super class"); } } class Flavor1Demo { // An anonymous class with Demo as base class static Demo d = new Demo() { void show() { super.show(); System.out.println("i am in Flavor1Demo class"); } }; public static void main(String[] args){ d.show(); } }