If I have a class such as:
class Person {
private String name;
...constructor, getters, setters, equals, hashcode, tostring...
}
Can I subclass and apply annotations to the name field in the subclass, for example to apply persistence annotations, without re-implementing the rest of the class?
@Entity
class Employee extends Person {
@Column(...)
private String name;
}
Annotations, just like methods or fields, can be inherited between class hierarchies. If an annotation declaration is marked with @Inherited , then a class that extends another class with this annotation can inherit it.
Annotations on methods are not inherited by default, so we need to handle this explicitly.
Annotation Type Inherited If an Inherited meta-annotation is present on an annotation type declaration, and the user queries the annotation type on a class declaration, and the class declaration has no annotation for this type, then the class's superclass will automatically be queried for the annotation type.
A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.
That wont work since the fields in super class 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);
}
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With