Can parent and child class in Java have same instance variable?

后端 未结 4 1367
说谎
说谎 2020-12-15 21:43

Consider these classes:

class Parent {
 int a;
}

class Child extends Parent {
 int a; // error?
}

Should the declaration of a

4条回答
  •  天命终不由人
    2020-12-15 22:11

    child.a shadows (or hides) parent.a.

    It's legal Java, but should be avoided. I'd expect your IDE to have an option to give you a warning about this.

    Note, however, that this is only an issue because you're already exposed a variable to the world. If you make sure that all your variables are private to start with (separating out the API of methods from the implementation of fields) then it doesn't matter if both the parent and the child have the same field names - the child wouldn't be able to see the parent's fields anyway. It could cause confusion if you move a method from the child to the parent, and it's not generally great for readability, but it's better than the hiding situation.

提交回复
热议问题