-1

动物类的以下代码中,当我删除ClimbTrees()方法时,为什么它会生成错误

public class Refr1 
{
    public static void main(String[] args) 
    { 
      Animal objChimp = new Chimp();
      objChimp.ClimbTrees();     
    }
}


class Animal
{
    void ClimbTrees()
    {
     System.out.println("I am Animal Which Climb Tree");    
    }
}


class Chimp extends Animal 
{
    void ClimbTrees()
    {
        System.out.println("I am Chimp Which Climb Tree");  
    }
}

如果我删除 Animal 类中的ClimbTrees(),它会显示以下错误

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    The method ClimbTrees() is undefined for the type Animal
4

3 回答 3

1
when I remove the ClimbTrees() Method why is it generating Error

这仅仅是因为使用objChimp实例您可以调用Animal类中的方法。由于ClimbTrees()方法不在Animal课堂上,您会收到此错误。

编辑: 我认为您正在尝试学习覆盖和多态性。您应该在此处获得更多详细信息。在您的情况下,以下是正确的。我没有在下面的示例中向您解释 WHY 因素,我将把它留给您研究。

// a. You can call only methods/variables is Animal class using objChimp instance
// b. If you are calling overridden methods, the method in Chimp class will be called in run time
Animal objChimp = new Chimp();

// a. You can call methods/variables both in Animal class and Chimp class using objChimp instance
// b. If you are calling overriden methods, the method in Chimp class will be called in runtime
Chimp objChimp = new Chimp();
于 2013-03-30T01:35:48.027 回答
1

This is the error you will get - The method ClimbTrees() is undefined for the type Animal. Why does it happen ?

The compiler checks the static type of objChimp. It is animal. The dynamic type of objChimp is Chimp.

The compiler first checks if there is a method called ClimbTrees() in the static type of objChimp. If it does not find it, then it throws an error. But, when you don't remove the method, the compiler sees the static type and finds ClimbTrees(). Only when it finds that, it will let you compile your code. During run time, its checked if there is also a ClimbTrees() in the dynamic type of objChimp. If found, then execute the ClimbTrees() of chimp and not of animal. If not found, then execute ClimbTrees() of static type of objChimp, that is ClimbTrees() of Animal (comment the climb trees of chimp and see what happens).

Notes -

http://en.wikipedia.org/wiki/Type_system

于 2013-03-30T01:37:42.603 回答
0

Since your objChimp is declared from Animal type, you can only use the Animal attributes/methods which you have access. If you want to call a specific attribute/method from a child, you should downcast it. This can make your code work (assuming you deleted ClimbTrees method from Animal class):

Animal objChimp = new Chimp();
((Chimp)objChimp).ClimbTrees(); 

However, you must be sure you can downcast the class to the specific class. Check Downcasting in Java for more info.

于 2013-03-30T01:36:06.600 回答