Skip to content

Casting

Keyhan Hadjari edited this page Sep 20, 2016 · 1 revision
public class Vehhicle {
    public void maxSpeed() {
        System.out.println("50");
    }
}

public class Car extends Vehicle {
    public void maxSpeed() {
        System.out.println("300");
    }

}

Car myCar = new Car();
Vehicle myVehicle = myCar; // Simple Casting, no need for parantheses
myVehicle.maxSpeed(); // prints 300 because of overriding in Car class;

Vehicle onlyVehicle = new Vehicle();
onlyVehicle.maxSpeed(); // prints 50


Car myCarAgain = (Car) myVehicle; // Explicit casting, has to use parantheses and class name

Car noCar = (Car) onlyVehicle; // Exception is thrown at runtime.

String boo = (String) myCar; // Compilation Error

Clone this wiki locally