2

Let us say that we have a class from API which has some fields, of which some are made mandatory using @NotNull annotation, like below:

class SomeAPIClass {

    private String field1;
    private String field2;

    @NotNull
    public String getField1() {
        return field1;
    }

    public String getField2() {
        return field2;
    }

    public void setField1(String field1) {
        this.field1 = field1;
    }

    public void setField2(String field2) {
        this.field2 = field2;
    }

}

Now we have extended this class and added some of our own attribute field3, however, we do not wish to use field1 (which is mandatory).

class SomeCustomClass extends SomeAPIClass {

    private String field3;

    public String getField3() {
        return field3;
    }

    public void setField3(String field3) {
        this.field1 = field1;
    }

}

But as field1 is defined as mandatory field in API class, which cannot be touched/changed there, it is failing validation. Is there any way I can get rid of that annotation in child class SomeCustomClass?

Szymon Jednac
  • 2,969
  • 1
  • 29
  • 43
Rupesh Vislawath
  • 125
  • 1
  • 11
  • maybe extending the parent class of that API class instead if its not a direct subclass of Object – johnII Dec 28 '17 at 15:18
  • 2
    Instead of using inheritance maybe have a look at [composition](https://en.wikipedia.org/wiki/Object_composition) – Lino Dec 28 '17 at 15:22
  • 5
    "Derived classes must be substitutable for their base classes." - Liskov principle of OOP. meaning that you have a flaw in the design that led to the problem you are facing. when inheriting from a parent class you should not change its contract. – RaniDevpr Dec 28 '17 at 15:23
  • 3
    If the parent class says that a method will never return null, a subclass cannot return null. Otherwise it is not substitutable. – Andy Turner Dec 28 '17 at 15:25
  • I agree with what 's been said, but, if you really **have to**... did you try overriding the method? – Ray O'Kalahjan Dec 28 '17 at 15:29
  • @RayO'Kalahjan, Yes I did try overriding and also tried Variable hiding(declaring same variable & its getters/setters in child class), but still validation fails. – Rupesh Vislawath Dec 28 '17 at 17:23
  • @Lino, Composition is not an option for me, as there are many dependencies on that class – Rupesh Vislawath Dec 28 '17 at 17:26
  • 3
    Java annotation are not inherited but it looks like constraint annotation are checked by validators across inheritance chain. https://stackoverflow.com/questions/9067420/can-i-override-a-jsr-303-validation-annotation – tsolakp Dec 28 '17 at 17:36

0 Answers0