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

后端 未结 10 1934
暗喜
暗喜 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:00

    upcasting means casting the object to a supertype, while downcasting means casting to a subtype.

    In java, upcasting is not necessary as it's done automatically. And it's usually referred as implicit casting. You can specify it to make it clear to others.

    Thus, writing

    Animal a = (Animal)d;
    

    or

    Animal a = d;
    

    leads to exactly the same point and in both cases will be executed the callme() from Dog.

    Downcasting is instead necessary because you defined a as object of Animal. Currently you know it's a Dog, but java has no guarantees it's. Actually at runtime it could be different and java will throw a ClassCastException, would that happen. Of course it's not the case of your very sample example. If you wouldn't cast a to Animal, java couldn't even compile the application because Animal doesn't have method callme2().

    In your example you cannot reach the code of callme() of Animal from UseAnimlas (because Dog overwrite it) unless the method would be as follow:

    class Dog extends Animal 
    { 
        public void callme()
        {
            super.callme();
            System.out.println("In callme of Dog");
        }
        ... 
    } 
    

提交回复
热议问题