What is the difference between up-casting and down-casting with respect to class variable

后端 未结 10 1766
暗喜
暗喜 2020-11-22 09:55

What is the difference between up-casting and down-casting with respect to class variable?

For example in the following program class Animal contains only one method

10条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 10:08

    Down-casting and up-casting was as follows:

    Upcasting: When we want to cast a Sub class to Super class, we use Upcasting(or widening). It happens automatically, no need to do anything explicitly.

    Downcasting : When we want to cast a Super class to Sub class, we use Downcasting(or narrowing), and Downcasting is not directly possible in Java, explicitly we have to do.

    Dog d = new Dog();
    Animal a = (Animal) d; //Explicitly you have done upcasting. Actually no need, we can directly type cast like Animal a = d; compiler now treat Dog as Animal but still it is Dog even after upcasting
    d.callme();
    a.callme(); // It calls Dog's method even though we use Animal reference.
    ((Dog) a).callme2(); // Downcasting: Compiler does know Animal it is, In order to use Dog methods, we have to do typecast explicitly.
    // Internally if it is not a Dog object it throws ClassCastException
    

提交回复
热议问题