为什么这两个代码示例产生不同的输出? [英] Why do these two code samples produce different outputs?

查看:112
本文介绍了为什么这两个代码示例产生不同的输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例1:

 class Animal {
     public static void saySomething() { System.out.print(" Gurrr!"); 
   }
 }
 class Cow extends Animal {
    public static void saySomething() { 
     System.out.print(" Moo!"); 
    }
    public static void main(String [] args) {
         Animal [] animals = {new Animal(), new Cow()};
         for( Animal a : animals) {
           a.saySomething();
         }
         new Cow().saySomething();
    }
 }

输出为:

 Gurrr! Gurrr! Moo!

样本2:

 class Animal {
     public void saySomething() { System.out.print(" Gurrr!"); 
   }
 }
 class Cow extends Animal {
    public void saySomething() { 
     System.out.print(" Moo!"); 
    }
    public static void main(String [] args) {
         Animal [] animals = {new Animal(), new Cow()};
         for( Animal a : animals) {
           a.saySomething();
         }
         new Cow().saySomething();
    }
 }

输出:

 Gurrr! Moo! Moo!

我只是不明白为什么说saySomething非静态导致第二次调用saySomething调用Cow版本而不是动物版本。我的理解是 Gurrr!哞! Moo!将是两种情况下的输出。

I just don't understand why making saySomething non-static causes the second call to saySomething invoke the Cow version instead of the Animal version. My understanding was that Gurrr! Moo! Moo! would be the output in either case.

推荐答案

静态方法绑定到他们的类编译时间不能多态使用。当您在Animal上声明一个静态方法时,它将永远绑定到Animal类,并且不能被覆盖。静态方法绑定到Class对象,而不是Class的实例。

static methods are bound to their class at compile time and cannot be used polymorphically. When you declare a "static" method on Animal, it is forever bound to the Animal class and cannot be overridden. Static methods are bound to the Class object, not an instance of the Class.

常规方法在运行时绑定,因此JVM可以查看对saySomething的调用并试图确定你是否传递了Animal的子类,如果是,它是否覆盖了 saySomething()方法。常规方法绑定到一个对象的实例,而不是绑定到Class本身。

Regular methods are bound at runtime and so the JVM can look at your call to "saySomething" and attempt to determine if you're passing around a subclass of Animal and if so, has it overridden the saySomething() method. Regular methods are bound to an instance of an object, not to the Class itself.

这也是你永远不能这样做的原因:

This is also why you could never do this:

class Animal
{
   public abstract static void saySomething();
}

由于静态意味着在编译时绑定,因此它永远不会有意义因为某些东西是静态的和抽象的。

Since "static" means "bound at compile time", it never makes sense for something to be static and abstract.

这篇关于为什么这两个代码示例产生不同的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆