INHERITANCE IN
JAVA
Nipun Lingadally-22211A05L5
Agenda
INTRODUCTION
TYPES OF INHERITANCE
SINGLE INHERITANCE
MULTI-LEVEL INHERITANCE
HIERARCHICAL INHERITANCE
Introduction
Inheritance in Java is a mechanism in which
one object acquires all the properties and
behaviors of a parent object. It is an important
part of OOPs (Object Oriented programming
system).
Inheritance is a fundamental concept in Java
where a class can inherit properties (methods
and fields) from another class.
It promotes code reusability, reduces
redundancy, and enhances code organization
Types of Inheritance
Hierarchical
Single Multi-level
Inheritance
Inheritance Inheritance
Multiple subclasses
A subclass inherits from A subclass inherits from
inherit from a single
only one superclass. another subclass.
superclass.
Definition
When a class inherits another class, it is known as a
single inheritance. In the example given below, Dog class
inherits the Animal class, so there is the single
inheritance.
Single Syntax
class Super {
Inheritance }
// properties and methods
class Sub extends Super {
// properties and methods
}
OUTPUT:
Example eating....
class Animal{ barking....
void eat(){
System.out.println("eating...");
}
}
class Dog extends Animal{
void bark(){
System.out.println("barking...");
}
}
class TestInheritance{
public static void main(String[] args){
Dog d=new Dog();
d.bark();
d.eat();
}
}
Definition
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.
Multi-level Syntax
class Super1 {
Inheritance }
// properties and methods
class Super2 extends Super1 {
// properties and methods
} class Sub extends Super2 {
// properties and methods
}
Example OUTPUT:
eating....
class Animal{ barking....
void eat(){ weeping....
System.out.println("eating...");
} }
class Dog extends Animal{
void bark(){
System.out.println("barking...");
} }
class BabyDog extends Dog{
void weep(){
System.out.println("weeping...");
} }
class TestInheritance2{
public static void main(String[] args){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
} }
Definition
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.
Hierarchical Syntax
class Super {
// properties and methods
Inheritance }
class Sub1 extends Super {
// properties and methods
}
class Sub2 extends Super {
// properties and methods
}
Example OUTPUT:
eating....
barking....
class Animal{
meowing....
void eat(){
System.out.println("eating...");
} }
class Dog extends Animal{
void bark(){
System.out.println("barking...");
} }
class Cat extends Animal{
void meow(){
System.out.println("meowing...");
} }
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
}}
Thank You