pitfall fields

However, only ordinary method calls can be polymorphic; java

For example: if you access a field directly , that access will be resolved at complie timethis

public class public_field_ {
	public static void main(String[] args) {
		Super sup = new Sub();
		/**
		 * output: 0;
		 */
		System.out.println(sup.field);
		/**
		 * output: 1;
		 */
		sup.getField();
	}
}
class Super {
	public int field =0;
	public void getField() {
		System.out.println(field);
	}
}
class Sub extends Super {
	 public int field = 1;
	public void getField() {
		System.out.println(field);
	}
	public void getSuperField() {
		System.out.println(super.field);
	}
}
in this example , diffrent storage is allocated for Super.field and Sub.field. Thus ,Sub actually contains two fields called field;
相關文章
相關標籤/搜索