在类中有两个具有相同名称的变量在Java中扩展另一个类

在类中有两个具有相同名称的变量在Java中扩展另一个类

问题描述:

以下是我的项目代码的一部分:

Following is a part of my code for a project:

public class Body extends Point{
    public double x, y, mass;

    public Body() {
        x = y = mass = 0;
    }

    public Body(double x, double y, double mass) {
        this.mass = mass;
        this.x = x;
        this.y = y;
    }
}

public class Point {
    public double x;
    public double y;

    public Point(double x, double y) {
        this.x = x;
        this.y = y;
    }
}



我很快意识到这样做会创建两个变量在Body类中调用x,另外两个变量在Body中调用y。

I quickly realized that doing this will create two variables inside the Body class called x and two other variables in Body called y. How is this even possible, and why on earth does Java even allow it?

我假设这是Body类的正确代码:

I assume this is the correct code of class Body:

public class Body extends Point{
    public double mass;

    public Body() {
        super();
        mass = 0;
    }

    public Body(double x, double y, double mass) {
        super(x,y);
        this.mass = mass;
    }
}

感谢您的时间

在某种意义上,你是覆盖超类的字段。但是它更容易意外,因为没有重载字段(你只有一个给定的名称的变量,类型不重要)。这被称为变量隐藏或阴影。所以,你是正确的,你会得到两个相同名字的字段。

In a sense, you are overriding fields of the super class. But it's far easier to do accidentally because there is no overloading of fields (you only have one variable of a given name, the type doesn't matter). This is referred to as variable 'hiding' or 'shadowing'. So, you're correct, you'll end up with two fields with the same name.

你的第二个例子是正确的。它们继承自超类,因为它们没有被声明为私有的,所以它们对子类是可见的。通常直接引用一个超类的字段是不好的做法,除非有很好的理由,他们应该声明为私有的。你调用超级构造函数的例子是最好的方法。

Your second example is correct. They are inherited from the super-class and since they are not declared private, they are visible to the subclass. It's generally bad practice to refer directly to a super-class's fields, and unless there is good reason, they should declared private. Your example of invoking the super constructor is the best approach.

此外,如果你用另一个相同的名字隐藏一个字段,你仍然可以将它们称为超级。 x,super.y,vs. this.x,this.y,你应该避免这种情况,如果可能的话。

Also, if you hide a field with another of the same name, you can still refer to them as super.x, super.y, vs. this.x, this.y, you should avoid this situation if at all possible.