Java-Java中this的疑惑

发布于 2017-02-02 07:56:44 字数 452 浏览 1116 评论 1

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

虐人心 2017-10-11 10:44:59

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文