Inheritance in Java

         Inheritance in Java is used to access all the properties and behaviors of Parent class. Basically, it increases the reusability of code and removes the redundancy of code.

    - We can inherit a class in Java using extends keyword.

    - Inheritance represents parent-child relation.

Consider the following scenario:

     class Bike{

        int numberOfWheels=2;

        String color;

        public Bike(String color){

            this.color = color;

        }

        public String getColor(){

            return this.color;

        }

    }


     class Car{

        int numberOfWheels=4;

        String color;

        boolean hasDisplayScreen = true;

        public Car(String color){

            this.color = color;

        }

        public String getColor(){

            return this.color;

        }

    }

        Here Bike and Car are two different classes with different features, but if you'll notice there are some properties and behaviors which are common such as noOfWheels, color, getColor() in above example. It unnecessarily increases number of statements and decreases the readability. Hence we can use inheritance by defining another class Vehicle as:

    class Vehicle {

        int numberOfWheels;

        String color;

        public Vehicle(int noOfWheels, String color){

            this.numberOfWheels = noOfWheels;

            this.color = color;

        }

        public String getColor(){

            return this.color;

        }

    }

 class Bike extends Vehicle{

        public Bike(int noOfWheels, String color){

            super(noOfWheels, color);

        }

    }


class Car extends Vehicle{

    boolean hasDisplayScreen = true;

    public Car(int noOfWheels, String color){

        super(noOfWheels, color);

    }

}


class Program{

    public static void main(String[] args){

        Bike bike = new Bike(2, "blue");

        Car car = new Car(4, "red");

        System.out.println("Color of bike: " + bike.getColor());   //Output: blue

        System.out.println("Color of Car: " + car.getColor()); //Output: red

    }

}

        As you can see that using inheritance we have access to getColor() method of Parent class Vehicle. 

So using inheritance, you can reuse methods and properties of parent class as well as can add more methods and fields(just like hasDisplayScreen field in Car class) in your current class. 


To know more about Types of Inheritance: click here

Comments

Popular Posts