Inheritance in Java

 Inheritance in Java

  • Inheritance is an important pillar of OOP(Object Oriented Programming). 
  • It is the mechanism in java by which one class is allow to inherit the features(fields and methods) of another class.


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
How to use inheritance in Java:-

The keyword used for inheritance is extends.

Syntax :

class derived-class extends base-class     

{  

   //methods and fields  

Example :-

class Employee

{  

 float salary=40000;  
}  
class Programmer extends Employee

{  
                 int bonus=10000;  
                 public static void main(String args[])

{  
               Programmer p=new Programmer();  
               System.out.println("Programmer salary is:"+p.salary);  
    System.out.println("Bonus of Programmer is:"+p.bonus);  
        }  
output:-Programmer salary is:40000.0  

Bonus of programmer is:10000

Types of inheritance in java:-

On the basis of class, there can be three types of inheritance in java: 
1.single
2.multilevel 
3.hierarchical.

1.single:-
Example:-
class Animal
{  
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();  
            }
}  

       2.Multilevel :-


Example:-

class Animal
{  
void eat()
{
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();  
            }
}  
 
3.Hierarchical Inheritance :-

 
Example:-
class Animal{  
   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();  
}
}  


Multiple Inheritance

Multiple Inheritance A class's capacity to inherit traits from several classes is referred to as multiple inheritances. This notion may be quite helpful when a class needs features from many sources.

Inheritance in Java

Multiple inheritances, however, can result in issues like the diamond problem, which occurs when two superclasses share the same method or field and causes conflicts. Java uses interfaces to implement multiple inheritances in order to prevent these conflicts.

import java.io.*;


interface Vehicle {

    

    // Abstract methods defined

    void changeGear(int a);

    void speedUp(int a);

    void applyBrakes(int a);

}


// Class implementing vehicle interface

class Bicycle implements Vehicle{

    

    int speed;

    int gear;

    

    // Change gear

    @Override

    public void changeGear(int newGear){

        gear = newGear;

    }

    

    // Increase speed

    @Override

    public void speedUp(int increment){

        speed = speed + increment;

    }

    

    // Decrease speed

    @Override

    public void applyBrakes(int decrement){

        speed = speed - decrement;

    }

    

    public void printStates() {

        System.out.println("speed: " + speed

            + " gear: " + gear);

    }

}


// Class implementing vehicle interface

class Bike implements Vehicle {

    

    int speed;

    int gear;

    

    // Change gear

    @Override

    public void changeGear(int newGear){

        gear = newGear;

    }

    

    // Increase speed

    @Override

    public void speedUp(int increment){

        speed = speed + increment;

    }

    

    // Decrease speed

    @Override

    public void applyBrakes(int decrement){

        speed = speed - decrement;

    }

    

    public void printStates() {

        System.out.println("speed: " + speed

            + " gear: " + gear);

    }

    

}


class Main

{    

    public static void main (String[] args) 

    {

    

        // Instance of Bicycle(Object)

        Bicycle bicycle = new Bicycle();

        

      bicycle.changeGear(2);

        bicycle.speedUp(3);

        bicycle.applyBrakes(1);

        

        System.out.print("Bicycle present state : ");

        bicycle.printStates();

        

        // Instance of Bike (Object)

        Bike bike = new Bike();

        bike.changeGear(1);

        bike.speedUp(4);

        bike.applyBrakes(3);

        

        System.out.print("Bike present state : ");

        bike.printStates();

    }

}

Multiple Inheritance in Java Using Interface

Java does not support multiple inheritance with classes to avoid ambiguity, but it supports multiple inheritance using interfaces.

Intefaces-in-Java-2-


import java.io.*;

// Add interface
interface Add{
    int add(int a,int b);
}

// Sub interface
interface Sub{
  int sub(int a,int b);
}

// Calculator class implementing Add and Sub 
class Cal implements Add , Sub
{
  // Method to add two numbers
  public int add(int a,int b){
      return a+b;
    }
  
  // Method to sub two numbers
  public int sub(int a,int b){
    return a-b;
    }
  
}

class GFG{
    // Main Method
    public static void main (String[] args) 
    {
      // instance of Cal class
      Cal x = new Cal();
      
      System.out.println("Addition : " + x.add(2,1));
      System.out.println("Substraction : " + x.sub(2,1));
      
    }
}

Comments

Popular posts from this blog

Java Package

Life cycle of a Thread and creating thread class