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

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

    Better try this method for upcasting, it's easy to understand:

    /* upcasting problem */
    class Animal
    { 
        public void callme()
        {
            System.out.println("In callme of Animal");
        }
    }
    
    class Dog extends Animal 
    { 
        public void callme()
        {
            System.out.println("In callme of Dog");
        }
    
        public void callme2()
        {
            System.out.println("In callme2 of Dog");
        }
    }
    
    public class Useanimlas 
    {
        public static void main (String [] args) 
        {
            Animal animal = new Animal ();
            Dog dog = new Dog();
            Animal ref;
            ref = animal;
            ref.callme();
            ref = dog;
            ref.callme();
        }
    }
    

提交回复
热议问题