java的静态绑定和动态绑定

看如下代码
abstract class F {

	private String foo = "foo in F";
	public abstract String getStupidName();

	public void bar() {
		System.out.println(this.getStupidName());
	}
}

class S1 extends F {
	private String foo = "foo in S1";

	@Override
	public String getStupidName() {
		return foo;
	}

}

class S2 extends F {
	private String foo = "foo in S2";

	@Override
	public String getStupidName() {
		return foo;
	}

		F f = new S1();
		f.bar();
		f = new S2();
		f.bar();

的输出是
foo in S1
foo in S2
显而易见,java的method的绑定是动态绑定的,但是field如何绑定呢,把F的代码改成如下形式
abstract class F {

	private String foo = "foo in F";
	public abstract String getStupidName();

	public void bar() {
		System.out.println(this.foo);
	}
}

输出则变成了
foo in F
foo in F

看上去field是静态绑定的

不过java specification似乎也是这么说的
http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.11

里面提到
Note that only the type of the Primary expression, not the class of the actual object referred to at run-time, is used in determining which field to use.

This lack of dynamic lookup for field accesses allows programs to be run efficiently with straightforward implementations. The power of late binding and overriding is available, but only when instance methods are used.

你可能感兴趣的:(J2SE)