07 August 2017

OOP- Polymorphism Example

Example:

Define a Vehicle interface

public interface Vehicle {
    int getNumberOfTyres();

}

Define a Bus Class which implements Vehicle interface

public class Bus implements Vehicle {
    public int getNumberOfTyres() {
        return 6;
    }
}

Define a Car Class which implements Vehicle interface

public class Car implements Vehicle {
    public int getNumberOfTyres() {
        System.out.println();
        return 4;
    }
}

Define a Vehicle Service and execute the main program

public class VehicleService {

    public static void main(String args[]){
        Vehicle veh = new Bus();
        //Method on Bus class will be executed
        System.out.println("Number of Bus Tyres = "+veh.getNumberOfTyres());
        Vehicle veh = new Car();
       //Method on Car class will be executed
System.out.println("Number of Car Tyres = "+veh.getNumberOfTyres()); } }
Output will be like :
Number of Bus Tyres = 6
Number of Car Tyres = 4
which class method needs to be executed will be decided at run time and it is based on the created object.