1

I'm completely confused how Lombok is supposed to be used in the following scenario:

Base class:

@Data
public abstract class BaseClass {

    protected final String foo;
    protected final String bar;
}

Subclass:

@Data
public class SubClass extends BaseClass {
    private final String bazz;
}

Lombok complains about the @Data annotation on the second class that it needs a default constructor in the base class. However, the fields in the base class are final, so a default constructor would have to initialize all fields to some value, which is messy, since they can't then be changed by the constructor of the sub class.

What is the correct way to set up these classes such that the concrete subclass can be created via a constructor with arguments? Can a builder be used with the final fields? I would like to avoid writing code as much as possible and rely on Lombok annotations (although I am aware this may not be possible).

Boon
  • 1,073
  • 1
  • 16
  • 42
  • Please check that your code compiles before posting. You forgot a keyword. – Michael Jun 25 '19 at 11:35
  • It's not possible https://github.com/rzwitserloot/lombok/issues/1229 – Michael Jun 25 '19 at 11:39
  • Without a constructpr, your BaseClass would have to provide values for foo and bar anyway, so I don't see why having a constructor is any messier. – racraman Jun 25 '19 at 11:40
  • You can use `@EqualsAndHashCode(callSuper = true)`, `@ToString` and `@Getter` on the subclass, you just need to define the constructor yourself. It's 5 lines of code, excluding the annotations – Michael Jun 25 '19 at 11:41
  • I can confirm that eclipse / lombok combination is messed up when it comes to final fields. For example, if you try to use `@AllArgsConstructor` to initialize a final field, youll get an IDE error saying that you need to initialize the final field. However if you write out that same constructor, you're good to go. I've been initializing final fields in my constructors for years, but `@AllArgsConstructor` doesn't like it for whatever reason. – Nate T Jun 08 '21 at 10:08

0 Answers0