【问题标题】:Why does this.<variable> or this.<method()> in Parent Class have no effect? Java为什么父类中的 this.<variable> 或 this.<method()> 没有效果?爪哇
【发布时间】:2020-02-18 21:53:52
【问题描述】:

我想知道为什么 this.(...) 在这种情况下没有效果。以下是我的考试任务:

class PARENT {
    public int x;
    public PARENT(int a)    {this.x = a;}

    public int getX()   {return this.x;}
    public int getY()   {return this.getX();}
}

class CHILD1 extends PARENT {
    public int x;
    public CHILD1(int b) {super(b); this.x = 2 * b;}
}

class CHILD2 extends PARENT {
    public CHILD2(int c)    {super(c);}

    public int getX()   {return 5;}
}

public class ThisTestMain {
    public static void main(String[] args)  {
        PARENT PP = new PARENT(10);
        PARENT PC1 = new CHILD1(100);
        PARENT PC2 = new CHILD2(1000);
        System.out.println(PP.getY());
        System.out.println(PC1.getY());
        System.out.println(PC2.getY());

        CHILD1 CC = new CHILD1(10);
        System.out.println(CC.getY());
    }
}

输出是:

10
100
5
10

我现在的问题是为什么System.out.println(PC1); 的输出不是200。因为当我在 IntelliJ 中调试代码时,我可以看到 this 有参考 CHILD1@799 和对象可以看到值xPARENT.x

此时为什么getX()选择PARENT.x而不是CHILD1.x

通过覆盖方法this 也没有效果。在这种情况下,例如System.out.println(PC2);CHILD2 中始终使用getX(),无论您是在getY() 方法中写入return this.getX(); 还是return getX();

有人可以总结一下这背后的系统吗?也许还考虑super?谢谢!

【问题讨论】:

    标签: java inheritance subclass


    【解决方案1】:

    CHILD1 定义了一个名为x 的新字段,它遮蔽字段xPARENT 中。删除字段。喜欢

    class CHILD1 extends PARENT {
        // public int x;
        public CHILD1(int b) {super(b); this.x = 2 * b;}
    }
    

    【讨论】:

    • 谢谢,但我想知道为什么 CHILD1 中的“int x”不会影响 PARENT 中的“int x”。尤其是当我使用“this.x”从 CHILD1 获取自我参考时
    • 因为实例变量不像方法那样被覆盖。 CHILD1 方法将访问 CHILD1 的 x,但 PARENT 的方法将访问 PARENT 的 x - 有关详细信息,请参阅 stackoverflow.com/questions/12086298/…
    • 您的示例中有两个 int x 变量,位于 CHILD1 中。对于PARENTint x,您可以使用super.x(但最好不要隐藏字段,否则会“破坏”继承)。
    • 感谢@racraman 提供链接,现在我了解情况了。 @Elliott Frisch 我仍然不明白你的意思,因为显然你不能从PARENT.getX 访问CHILD1.x,因为方法只能看到他自己类中的变量。您只能通过覆盖 CHILD1 中的方法来访问它,因此 super.x 是多余的。 (this.x 也)
    • “方法只看到他自己类中的变量。” - 不完全。方法可以在自己的类中看到变量,也可以在超类中看到受保护/公共变量。这意味着 CHILD1 方法可以访问 PARENT1 变量,但只是在这种情况下 PARENT1 变量被同名的 CHILD1 变量所遮蔽 - 因此 CHILD1 方法可以使用 super.x 语法来访问 PARENT1 变量。还值得强调的是永远不要命名变量,这样它们就会像这样覆盖超类变量;在实际项目中避免这种情况:)
    【解决方案2】:

    在 CHILD1 中,您没有被覆盖的方法。

    因此,当您调用 getY() 时,它会从 PARENT 调用 getX()。来自 PARENT 的方法不知道其子类中的变量。

    您必须覆盖 CHILD1 中的 getX() 方法才能访问变量 CHILD1.x。

    【讨论】:

    • 谢谢!那么继承而不是覆盖的方法通常只能访问父类的变量(字段)?
    猜你喜欢
    • 1970-01-01
    • 2023-04-07
    • 2014-05-16
    • 1970-01-01
    • 2021-10-21
    • 2015-01-01
    • 2015-08-11
    • 1970-01-01
    • 2019-02-10
    相关资源
    最近更新 更多