Inheritance in Java

Now let us try to Inheritance in Java.

Inheritance allows child class to inherit the members of parent class. With inheritance concept, it is possible for one class to inherit the members of other class. Public and protected members of base class are inherited by child class.

Inheritance can be of 3 types in Java.

  1. Single inheritance
  2. Multi-level inheritance
  3. Hierarchical inheritance

Single Inheritance in Java

Multilevel Inheritance in Java

Hierarchical Inheritance in Java

 

Below example demonstrates all these concepts in detail.

package oops;

/**
 * Created by Sagar on 16-04-2016.
 */
public class ObjectOrientedClass {
    public static void main(String [] args){
        //Polymorphism can be of various type.
        //In below lines, we have used same Variable v1
        // to refer to different types of objects
        Vehicle v1 = new Truck();
        System.out.println("Fule type of Truck -> " + v1.fuelType);
        v1.start();
        v1 = new MotorCycle();
        System.out.println("Fule type of MotorCycle -> " + v1.fuelType);
        v1.start();

        //We can not access private members of any class
        //This concept is called as Encapsulation.
        //v1.passengerCapacity is invalid. Outside world does not know
        //what is going on inside a class.

        //Abstraction is achieved by using interfaces or abstract methods.
        //Below example is valid.
        Startable s = new MotorCycle();
        //Below example will call MotorCycle's start method.
        s.start();


    }
}

class Vehicle implements Startable{
    protected String fuelType;
    public int year;
    public void start(){
        //System.out.println("Vehicle start");
    }
}

//By inheritance, Truck and MotorCycle class gets protected 
// and public members of parent class Vehicle
class Truck extends Vehicle{
    private int GoodsCapacity;
    public Truck(){
        this.fuelType = "Diesel";
    }

    @Override
    public void start(){
        System.out.println("Truck start");
    }
}

class MotorCycle extends Vehicle{
    private int passengerCapacity;
    public MotorCycle(){
        this.fuelType = "Petrol";
    }
    @Override
    public void start(){
        System.out.println("MotorCycle start");
    }
}

interface Startable{
    void start();
}

Here is the output of above example.
Fule type of Truck -> Diesel
Truck start
Fule type of MotorCycle -> Petrol
MotorCycle start
MotorCycle start

You may also like...