2014-12-08 64 views
1

封装测试;呼叫继承的类的功能,但仍父类的功能被执行

公共类TestMain {

public static void main(String[] args) { 
    Animal cat = new Cat(); 
    cat.xyz(); 
} 

}

class Animal{ 
    public static void xyz(){System.out.println("Inside animal");} 
} 

class Cat extends Animal{ 
    public static void xyz(){System.out.println("Inside cat");} 
} 

输出:在内部猫类动物

[这里最好的xyz()应该已经执行,但它没有发生。相反,Animal类的xyz()正在执行。它只发生在我将这个xyz()函数设为静态时,否则就没有问题。 ] 请说明理由。

+1

您的问题类似于[这个问题] [1 ]请检查我的[answer there] [2] [1]:http://stackoverflow.com/questi ons/27345510/inheritance-in-java-subclass/27345630 [2]:http://stackoverflow.com/questions/27345510/inheritance-in-java-subclass/27345630#27345630 – Nazgul 2014-12-08 05:29:55

回答

0

的原因是因为使用的是static方法和static方法被称为为引用的类型。这不是重写方法,因为重写适用于实例方法而不适用于静态方法。

如果你让你的方法非静态然后xyz方法将取决于实例调用。

0

答案很简单。实例仅在运行时创建,即在执行静态方法之后创建。因此,当在呼叫XYZ的时间()变量猫仍然是一个动物不是猫。如果完全想要所需结果,请执行以下操作之一:

  1. 从方法签名中除去static关键字。

  • 呼叫的方法的xyz()之类的以下
  • public static void main(String[] args) { 
    Animal cat = new Cat(); // remove this line 
    Cat.xyz(); // you can call static methods directly using the class name. 
    }