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

后端 未结 4 1939
挽巷
挽巷 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:23

    Yes, you'll have two variables, with one hiding the other. It makes sense to allow it for two reasons:

    1. Suppose you've got a base class Base and a derived class Derived which the author of Base has no idea about. Should the author of Base never be able to add any fields, just because a derived class might share the fields? Or should Derived stop compiling when the change to Base doesn't actually affect the correctness?
    2. Your fields should almost always be private, at which point it doesn't matter whether the names are duplicated or not - neither "side" will know about the variables of the other.

提交回复
热议问题