Java 静态方法隐藏

Java 静态方法隐藏,java,Java,请看下面的代码: class Marsupial { public static boolean isBiped() { return false; } public void getMarsupialDescription() { System.out.println("Value of this : " + this.getClass().getName() + " , Marsupial walks on two legs: " +

请看下面的代码:

class Marsupial {
    public static boolean isBiped() {
        return false;
    }

    public void getMarsupialDescription() {
        System.out.println("Value of this : " + this.getClass().getName() + " , Marsupial walks on two legs: " + isBiped());
    }
}

public class Kangaroo extends Marsupial {
    public static boolean isBiped() {
        return true;
    }

    public void getKangarooDescription() {
        System.out.println("Value of this : " + this.getClass().getName() + ", Kangaroo hops on two legs: " + isBiped());
    }

    public static void main(String[] args) {
        Kangaroo joey = new Kangaroo();
        joey.getMarsupialDescription(); // Question here
        joey.getKangarooDescription();
    }

}
输出为:

Value of this : Kangaroo , Marsupial walks on two legs: false
Value of this : Kangaroo, Kangaroo hops on two legs: true

现在为什么在getMarsupialDescription()的调用中,它会选择有袋动物的静态方法而不是袋鼠的静态方法,特别是当
这个
指向
袋鼠的时候

简单地说,方法调用与方法体的关联是一种绑定类型。有两种类型的绑定:编译时发生的静态绑定和运行时发生的动态绑定

静态绑定或早期绑定

编译器可以在编译时解析的绑定称为静态绑定或早期绑定。静态、私有和最终方法的绑定是在编译时进行的。为什么?原因是无法重写这些方法,并且类的类型是在编译时确定的。让我们看一个例子来理解这一点:

class Human{
   public static void walk()
   {
       System.out.println("Human walks");
   }
}
class Boy extends Human{
   public static void walk(){
       System.out.println("Boy walks");
   }
   public static void main( String args[]) {
       /* Reference is of Human type and object is
        * Boy type
        */
       Human obj = new Boy();
       /* Reference is of HUman type and object is
        * of Human type.
        */
       Human obj2 = new Human();
       // At compile time it gets decided which body of method it will call
       obj.walk(); 
       obj2.walk();
   }
}
为什么是在编译时?因为它是静态的。 静态绑定是按引用类型而不是对象类型完成的

输出:

Human walks
Human walks
类似地,在上面讨论的代码中-isBiped()静态方法仅在编译时链接到方法体。因此它称为有袋动物isBiped()


静态方法永远不会被虚拟调用。它们总是在编译时绑定。静态方法的要点是,您不需要使用
这个
指针来调用它。@SilvioMayolo thnx可能与@SilvioMayolo重复这是否意味着静态方法隐藏只在编译时发生,因为静态绑定将在编译时绑定它?我不确定我是否完全理解您的问题,但我相信您是正确的。静态方法总是在编译时解析,因此如果在子类中使用相同的名称,那么也会在编译时解析。