How does the “this” keyword in Java inheritance work?

后端 未结 7 674
被撕碎了的回忆
被撕碎了的回忆 2021-02-02 09:23

In the below code snippet, the result is really confusing.

public class TestInheritance {
    public static void main(String[] args) {
        new Son();
                


        
7条回答
  •  佛祖请我去吃肉
    2021-02-02 10:09

    This is commonly referred to as shadowing. Note your class declarations:

    class Father {
        public String x = "Father";
    

    and

    class Son extends Father {
        public String x = "Son";
    

    This creates 2 distinct variables named x when you create an instance of Son. One x belongs to the Father superclass, and the second x belongs to the Son subclass. Based on the output, we can see that when in the Father scope, this accesses the Father's x instance variable. So the behavior is not related to "what this points to"; it's a result of how the runtime searches for instance variables. It only goes up the class hierarchy to search for variables. A class can only reference variables from itself and its parent classes; it can't access variables from its child classes directly because it doesn't know anything about its children.

    To obtain the polymorphic behavior you want, you should only declare x in Father:

    class Father {
        public String x;
    
        public Father() {
            this.x = "Father"
        }
    

    and

    class Son extends Father {
        public Son() {
            this.x = "Son"
        }
    

    This article discussed the behavior you're experiencing exactly: http://www.xyzws.com/Javafaq/what-is-variable-hiding-and-shadowing/15.

提交回复
热议问题