我已经搜索了关于堆栈溢出的后期绑定的所有类似问题,并且我会严重不同意将这个问题标记为重复的任何人。首先,我在另一个问题上找到了这个例子,但是我不明白在编译期间何时决定什么时候以及何时在运行时决定什么时我应该知道该怎么做。基本上,我的问题的症结归结为两点:Java中的后期绑定
在什么这个例子必须带我到逻辑结论,一个方法是后期绑定而另一个早期绑定
如何我知道什么时候决定哪些执行方法的版本在运行时决定或编译时在Java中
代码:
class A
{
public void foo()
{
System.out.println("Class A");
}
}
class B extends A
{
public void foo()
{
System.out.println("Class B");
}
}
public class C
{
public static void main(String [] args)
{
A a=new A();
B b=new B();
A ref=null;
/*
early binding --- calls method foo() of class A and
decided at compile time
*/
a.foo();
/* early binding --- calls method foo() of class B and
decided at compile time
*/
b.foo();
/* late binding --- --- calls method foo() of class B and
decided at Run time
*/
ref=b;
ref.foo(); }
}
最后的静态或私有方法不会发生后期绑定。对于任何其他它确实如此。就这些。 – Pshemo
给未来读者的提示:上面代码中的注释不正确! –
如果我的回答很有帮助,您可以请修改意见然后 – user3163829