use*_*829 10 java late-binding
我已经搜索了有关堆栈溢出的后期绑定的所有类似问题,我会严重不同意将此问题标记为重复的任何人.首先,我在另一个问题上找到了这个例子,但是我不明白在编译期间什么时候决定什么以及什么时候在运行时决定了什么我应该知道.基本上,我的问题的症结归结为两件事:
本例中的内容必须使我得出一个逻辑结论:一个方法是后期绑定,另一个方法是早期绑定
我如何知道在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(); }
}
Run Code Online (Sandbox Code Playgroud)
在所有方面都错了.在此处,基于对象的运行时类型,在运行时决定要调用的方法.在编译时做出的唯一决定是调用final,private或static方法,或者在一组重载方法中进行选择(如果重载方法不是final,private或static,它们仍然可以导致运行时选择.)
Java 对所有非最终、非私有实例方法使用后期绑定。这就是多态性的实现方式。您评论的所有调用都是在运行时确定的。
在
A a=new A();
a.foo();
Run Code Online (Sandbox Code Playgroud)
a正在引用一个A对象,因此A将找到、绑定和使用 的实现。
在
B b=new B();
b.foo();
Run Code Online (Sandbox Code Playgroud)
b正在引用一个B对象,因此B将找到、绑定和使用 的实现。
在
ref=b;
ref.foo();
Run Code Online (Sandbox Code Playgroud)
ref正在引用一个B对象,因此B将找到、绑定和使用 的实现。
变量的静态(声明)类型仅由编译器用于验证此类方法是否可在该类型上访问。
有关的:
| 归档时间: |
|
| 查看次数: |
10861 次 |
| 最近记录: |