2017  Kodetalk | Feedback | Privacy Policy | Terms | About
userimage

Difference between Up-casting and Down-casting with respect to Class variable.

I want the clear explanation with example for Up-casting and Down-casting for class variable in java(not for primitive class).
userimage

Upcasting is like putting 5 kg rice in a 10 kg container.. there's enough space to put..so compiler does it automatically

Downcasting is vice versa...but in this case the compiler needs to know how much space it has available so it can put only what is possible..explicit cast does that


package com.test.code;

class Machine {
    public void start() {
        System.out.println("Machin started ...");
    }
}

class Camera extends Machine{
    public void start() {
        System.out.println("Camera started ...");
    }

    public void snap() {
        System.out.println("Picture taken ...");
    }
}

public class App {
    public static void main(String[] args) {
        Machine machine1 = new Machine();
        Camera camera1 = new Camera();

        machine1.start();
        camera1.start();
        camera1.snap();
       
        //up casting
        Machine machine2 = new Camera(); //automatically cast since all Camera are Machines
        machine2.start();
        //machine2.snap(); leads to exception
       
        //down casting
        Machine machine3 = new Camera();
        Camera camera2 = (Camera)machine3; // needs to cast manually because all machines are not Camera
        camera2.start();
        camera2.snap();
    }
}

Answer is