Inheritance & Its Types

Inheritance & Its Types

Do you know what is Inheritance in java?

Let me explain. Hii I'm Kalimullah Ansari and I'm going to explain inheritance and it's types with examples.

Inheritance is a characteristic of oops(object oriented programming) in which a super class and child class exists. A child class aquire all the properties of super/ parent class. This phenomena is called inheritance.

We can use " extends " keyword to inherit all the properties of parent class by child class.

eg:-

class parent

{

Void greet ()

{

System.out.println("Parent class of this program");

}

}

class child extends parent

{

Void name()

{

System.out.println("Child class of this program");

}

}

class main_Inherit

{

public static void main (String args[])

{

child obj = new child ();

obj.name();

obj.greet();

}

}

Types of Inheritance

  1. Single Inheritance

  2. Multi-level Inheritance

  3. Hierarchical Inheritance

  4. Multiple Inheritance

Single Inheritance :-

In single Inheritance there is a super class and a sub class.

eg :-

class Animal

{

Void eat()

{

System.out.println("Eating");

}

Void sleep()

{

System.out.println("sleeping");

}

}

class cat extends Animals

{

Void sound()

{

System.out.println("mew");

}

}

Class cat_animal

{

public static void main (String args [])

{

cat C = new cat();

C.eat();

C.sleep();

}

}

Multi-level Inheritance :-

In multi-level Inheritance there are a parent class and many child classes which inherit the characteristics of parent class.

Parent class ==> child class 1 ==> sub child class 2

This order to maintain in multi-level Inheritance.

eg :-

class grandParent

{

Void grandparent()

{

System.out.println(" Grand Parents);

}

}

class parent extends grandParent

{

Void Parent()

{

System.out.println("Parent");

}

}

class child extends parent

{

Void Child()

{

System.out.println("Child");

}

}

}

class multi_level

{

public static void main (String args[])

{

child obj = new child ();

obj.Child();

obj.Parent();

obj.grandparent();

}

}

Hierarchical Inheritance :-

eg :-

class Animal

{

Void sleep();

{

System.out.println("Sleeping");

}

Void eat()

{

System.out.println("Eating ");

}

}

class Cat extends Animal

{

Void sound ()

{

System.out.println("mew");

}

}

class Dog extends Animal

{

Void sound ()

{

System.out.println("bark");

}

}

class animal_spack

{

public static void main (String args [])

{

Cat c = new Cat();

c.sleep();

c.eat();

c.sound();

Dog d = new Dog();

d.sleep();

d.eat();

d.sound();

}

}

Java do not support multiple Inheritance directly.

We can use interface to execute multiple Inheritance.