简体   繁体   English

Java中子类为什么访问父类的字段而不是自己的?

[英]Why does the subclass access the parent's field but not their own in Java?

class Parent {
    int money = 10000;
    int getMoney() {
        return money;
    }
}

class Child extends Parent {
    int money = 5000;
}

public class Test {

    public static void main(String[] args) {

        Child c = new Child();
        System.out.println(c.getMoney());
    }
}

The output is 10000. Also if I edit the getter to say return this.money I get the same result. output 是 10000。另外,如果我编辑 getter 说return this.money我会得到相同的结果。

So why does Java take superclass's field but not the caller's ( Child ).那么为什么 Java 采用超类的字段而不是调用者的( Child )。 I know Python more and it shouldn't be like this in Python.我知道 Python 更多,在 Python 中不应该是这样的。

You can't override variables in Java.您不能覆盖 Java 中的变量。 The method is in the Parent class which means that money will access the variable in the Parent class also.该方法在Parent class 中,这意味着money也将访问Parent class 中的变量。

The thing that can be done in Java is hiding as opposed to overriding.在 Java 中可以做的事情是隐藏而不是覆盖。 If you declared the getter in the Child class then it would print 5000 as the Parent money variable has been hidden.如果您在Child class 中声明了 getter,那么它将打印5000 ,因为Parent money变量已被隐藏。


To address your edit about using this , it won't change anything.为了解决您对使用this的编辑,它不会改变任何东西。 By referencing a variable in a class, you're already implicitly referring to this .通过引用 class 中的变量,您已经隐含地引用了this

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM