upcasting - 调用子类对象时

时间:2012-06-16 07:12:42

标签: java casting

正在进行一个简单的向上转换子类(狗的对象被超类(Animal)引用...

为什么我无法调用方法'callme2()'

代码: -

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");
        }
    }

    class upcasting
    {
        public static void main (String [] args) throws Exception
        {
            Animal a = new Dog();     
    a.callme(); //-In call me of Dog       
    a.callme2(); // - error why ?
     }
    }

1 个答案:

答案 0 :(得分:3)

因为a已分配给超类Animal

您可以按以下方式调用该方法:

((Dog)a).callme2()