0

A simple upcasting is going on where the sub calss(dog)'s object is referenced by its super class(Animal)...

Why i am not able to call the method 'callme2()'

CODE:-

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 ?
     }
    }
4

1 回答 1

2

Because a is assigned to superclass Animal

You can call the methed as follow:

((Dog)a).callme2() 
于 2012-06-16T07:15:03.127 回答