Java-Java中this的疑惑
public class Test05 {
public static void main(String[] args) {
Father obj = new Son();
System.out.println(obj.name);
}
}
class Father{
public String name = "父类字段";
Father(){
System.out.println(this);
System.out.println(this.name);
}
}
class Son extends Father{
public String name = "子类字段";
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
JLS8:
https://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.1.6
If the class declares a field with a certain name, then the declaration of that field is said to hide any and all accessible declarations of fields with the same name in superclasses, and superinterfaces of the class.
In this respect, hiding of fields differs from hiding of methods (§8.4.8.3), for there is no distinction drawn between static and non-static fields in field hiding whereas a distinction is drawn between static and non-static methods in method hiding.
A hidden field can be accessed by using a qualified name (§6.5.6.2) if it is static, or by using a field access expression that contains the keyword super (§15.11.2) or a cast to a superclass type.
就是说, 父类的 同名字段被隐藏了, 可以通过 cast to a superclass type 来调用此字段.
public class Test05 {
public static void main(String[] args) {
Child obj = new Child();
System.out.println(obj.name);
System.out.println(((Father)obj).name);
}
}
class Father {
public String name = "Father";
}
class Child extends Father {
public String name = "Child";
}
结果:
Child
Father
字节码:
public static void main(java.lang.String[] args);
0 new Child [16]
3 dup
4 invokespecial Child() [18]
7 astore_1 [obj]
8 getstatic java.lang.System.out : java.io.PrintStream [19]
11 aload_1 [obj]
12 getfield Child.name : java.lang.String [25]
15 invokevirtual java.io.PrintStream.println(java.lang.String) : void [29]
18 getstatic java.lang.System.out : java.io.PrintStream [19]
21 aload_1 [obj]
22 getfield Father.name : java.lang.String [35]
25 invokevirtual java.io.PrintStream.println(java.lang.String) : void [29]
28 return