Having 2 variables with the same name in a class that extends another class in Java

后端 未结 4 1941
挽巷
挽巷 2020-12-31 04:29

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;
         


        
4条回答
  •  离开以前
    2020-12-31 05:17

    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.

    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.

提交回复
热议问题