Sarah Haskins
Sarah Haskins

Reputation: 1395

Lombok inheritance with @EqualsAndHashCode

I have a class which extends a parent class using @EqualsAndHashCode. I am getting a compilation error with Lombok 1.16.0 and Java 8

@EqualsAndHashCode(doNotUseGetters = true, of = { "propertyA", "propertyB" }) public class Parent {...}

@EqualsAndHashCode(callSuper = true, doNotUseGetters = true, of = { "propertyC", "propertyD" }) public class Child extends Parent {...}

The error is...

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project granger: Compilation failure [ERROR] /Users/sarah/src/main/java/com/xxx/Child.java:[26,1] canEqual(java.lang.Object) in com.xxx.Child cannot override canEqual(java.lang.Object) in com.yyy.Parent [ERROR] attempting to assign weaker access privileges; was public

Is there any best practice around inheritance and @EqualsAndHashCode and Lombok that I am abusing? Or any way around this?

Upvotes: 2

Views: 9352

Answers (2)

a better oliver
a better oliver

Reputation: 26848

It seems the classes are in different artifacts or you made an incremental build.

Before 1.14 canEqualwas public, since then it's protected.

If you make a clean and / or compile Parent using Lombok 1.16 it should work.

Upvotes: 2

lmm
lmm

Reputation: 17431

Even if you made this build you would end up with a broken equals method, because it won't be symmetric (parent.equals(child) if they have the same values in the parent fields, but never child.equals(parent)). It's been a while since I used Lombok, but scala case classes (which are more or less equivalent in this regard) cannot extend other case classes for this reason.

Think very carefully about what Parent and Child represent. Is Child really Liskov-substitutable for Parent? If so, it might be better to inherit the definition of equals and hashCode from Parent, and not try to redefine them in Child at all; if not, it might be better to extract the common functionality into a common superclass which both Parent and Child extend, rather than having them as parent and child.

Upvotes: 4

Related Questions