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: " + 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() 时,它会选择 Marsupial 的静态方法而不是 Kangaroo 的静态方法,特别是当 this 指向 Kangaroo 时?

最佳答案

简单地说,方法调用与方法体的关联就是绑定(bind)类型。 [What is binding ?]有两种类型的绑定(bind):编译时发生的静态绑定(bind)和运行时发生的动态绑定(bind)。

静态绑定(bind)或早期绑定(bind)

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

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();
   }
}

为什么是在编译时?因为它是静态的。 静态绑定(bind)是通过引用类型而不是对象类型来完成的。

输出:

Human walks
Human walks

类似地,在上面的代码中 - isBiped() 静态方法仅在编译时链接到方法的主体。因此它调用 Marsupial isBiped()。

What is static and dynamic binding ?

Source of above answer

关于java - 静态方法隐藏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49720828/

相关文章:

java - 如何从 EJB 计时器调用 @RolesAllowed protected 方法?

java - 注释主要是关于记录代码还是由编译器强制执行?

java - 使用来自 java 的自类型依赖项初始化 scala 类

java - 将所有内容都包含在一个 try-catch 中是个好主意吗

java - 根据特定条件替换 ViewPager fragment

java - 打开 Activity 错误

java - 找不到类型为 Org.springframework.mail.javamail.JavaMailSender 的 Bean?

Java 在没有正则表达式的情况下从 String 中删除 HTML

JavaFX : How to keep the VBox background color persistent?

java - Shell 脚本调用 java 可执行文件并捕获异常