Java-Applying Runtime Polymorphism

Applying Runtime Polymorphism

The following program creates a superclass called Car that stores the speed of a vehicle object. It also defines a method called topSpeed( ) that print the speed of an object. The program derives two subclasses from Car. The first is Ferrari and the second is Ford. Each of these subclass overrides topSpeed( ) so that it print the speed of a Ferrari and a Ford, respectively.

Program

final

Program Source

class Car{
    
    int speed;
    
    Car(int spd)
    {
        speed =spd;
    }
    
    void topSpeed()
    {
        System.out.println("Undefined Car");
    }
}

class Ferrari extends Car{
    
    Ferrari(int spd)
    {
        super(spd);
    }
    void topSpeed()
    {
        System.out.println("Ferrari Speed : "+speed);
    }
}

class Ford extends Car{
    
    
    Ford(int spd)
    {
        super(spd);
    }
    void topSpeed()
    {
        System.out.println("Ford Speed : "+speed);
    }
}

public class Javaapp {

    public static void main(String[] args) {
        
        Ferrari ferrari = new Ferrari(250);
        Ford ford = new Ford(300);
        Car car = new Car(200);
        
        Car ref;
        
        ref = ferrari;
        ref.topSpeed();
        
        ref = ford;
        ref.topSpeed();
        
        ref = car;
        ref.topSpeed();
    }
}

Leave a Comment