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

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

    I know this question asked quite long time ago but for the new users of this question. Please read this article where contains complete description on upcasting, downcasting and use of instanceof operator

    • There's no need to upcast manually, it happens on its own:

      Mammal m = (Mammal)new Cat(); equals to Mammal m = new Cat();

    • But downcasting must always be done manually:

      Cat c1 = new Cat();      
      Animal a = c1;      //automatic upcasting to Animal
      Cat c2 = (Cat) a;    //manual downcasting back to a Cat
      

    Why is that so, that upcasting is automatical, but downcasting must be manual? Well, you see, upcasting can never fail. But if you have a group of different Animals and want to downcast them all to a Cat, then there's a chance, that some of these Animals are actually Dogs, and process fails, by throwing ClassCastException. This is where is should introduce an useful feature called "instanceof", which tests if an object is instance of some Class.

     Cat c1 = new Cat();         
        Animal a = c1;       //upcasting to Animal
        if(a instanceof Cat){ // testing if the Animal is a Cat
            System.out.println("It's a Cat! Now i can safely downcast it to a Cat, without a fear of failure.");        
            Cat c2 = (Cat)a;
        }
    

    For more information please read this article

提交回复
热议问题