Is it possible to annotate an element inherited from a superclass?

If I have a class, for example:

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

Is it possible to subclass and apply annotations to the name field in a subclass, for example, to apply save annotations, without re-implementing the rest of the class?

 @Entity class Employee extends Person { @Column(...) private String name; } 
+4
source share
3 answers

No, you can’t.

What you propose is field shading - you cannot override a field.

The name field in the subclass has nothing to do with the name field in the superclass, except that it has the same name "name" and, thus, selects the field in the superclass, one should refer to it as super.name in the subclass.

In general, this is considered a β€œmistake” (or a potential mistake), and best practices are not shadow fields, because it is so easy to access the wrong field without knowing it.

+8
source

This does not work as the fields in the superclass will not be affected, but you can try this

 @Entity class Employee extends Person { @Column(name="xxx") @Override public void setName(String name) { super.setName(name); } ... 
+9
source

No - you will get two different fields. An annotated name field in Employee will hide the name field in the Person class. Person.name will not be annotated.

0
source

Source: https://habr.com/ru/post/1488273/


All Articles