Can I annotate a member inherited from a superclass?

前端 未结 4 676
一向
一向 2021-02-13 20:02

If I have a class such as:

class Person {
  private String name;
  ...constructor, getters, setters, equals, hashcode, tostring...
}

Can I subc

4条回答
  •  失恋的感觉
    2021-02-13 20:34

    No, you can't.

    What you are proposing is field shadowing - you can't override a field.

    The field name in the subclass has nothing whatsoever to do with the field name in the super class, other than it shares the same name of "name" and thus to distinguish the field in the super class, one must refer to it as super.name in the subclass.

    Doing this is generally considered a "bug" (or a potential bug anyway), and best practices are to not shadow fields, because it is so easy to refer to the wrong field without knowing it.

提交回复
热议问题