14

我对这里的代码有疑问

public Car {
    public static void m1(){
        System.out.println("a");
    }
    public void m2(){
        System.out.println("b");
    }
}

class Mini extends Car {
    public static void m1() {
        System.out.println("c");
    }
    public void m2(){
        System.out.println("d");
    }
    public static void main(String args[]) {
        Car c = new Mini();
        c.m1();
        c.m2();       
   }
}

我知道多态性不适用于静态方法,仅适用于实例方法。而且这种覆盖也不适用于静态方法。

因此我认为这个程序应该打印出:c, d

因为 c 调用了 m1 方法,但它是静态的,所以它不能覆盖,它调用的是 Mini 类中的方法,而不是 Car。

这个对吗?

但是,我的教科书说答案应该是:a,d

是错字吗?因为我现在有点迷茫。

请澄清一下,谢谢。

4

2 回答 2

36

因为 c 调用了 m1 方法,但它是静态的,所以它不能覆盖,它调用的是 Mini 类中的方法,而不是 Car。

那完全是倒退。

c声明Car,因此通过 进行的静态方法调用c将调用由 定义的方法Car
编译器c.m1()直接编译为Car.m1(),而不知道c实际上包含Mini.

这就是为什么你永远不应该通过这样的实例调用静态方法。

于 2012-12-04T04:19:15.647 回答
3

我在使用继承时遇到了同样的问题。我所学到的是,如果被调用的方法是静态的,那么它将从引用变量所属的类中调用,而不是从实例化它的类中调用。

 public class ParentExamp
    {                   
     public static void Displayer()
     {
      System.out.println("This is the display of the PARENT class");
     }
    }

     class ChildExamp extends ParentExamp
    {
        public static void main(String[] args)
        {
          ParentExamp a  = new ParentExamp();
          ParentExamp b  = new ChildExamp();
          ChildExamp  c  = new ChildExamp();

          a.Displayer(); //Works exactly like ParentExamp.Displayer() and Will 
                        call the Displayer method of the ParentExamp Class

          b.Displayer();//Works exactly like ParentExamp.Displayer() and Will 
                        call the Displayer method of the ParentExamp Class

          c.Displayer();//Works exactly like ChildExamp.Displayer() and Will 
                        call the Displayer method of the ChildtExamp Class
        }               
        public static void Displayer()
        {
         System.out.println("This is the display of the CHILD class");
        }   
    }

在此处输入图像描述

于 2020-05-16T18:41:30.747 回答