2

By creating a Java record

public record Rec(String foo, int bar) {}

one also gets a

public constructor whose signature is derived from the record components list

One can refine the behavior of this constructor by the so called compact constructor

public record Rec(String foo, int bar) {
    public Rec { /* ... */ }
}

What does not work, though, is making the constructor private.

public record Rec(String foo, int bar) {
    private Rec { }
}

java: invalid canonical constructor in record Rec (attempting to assign stronger access privileges; was public)

Is there any way to make the constructor of a record private?

In case someone is thinking why one would do such a thing. The record should be extended with a builder. To enforce using the builder the constructor should be private.

Naman
  • 27,789
  • 26
  • 218
  • 353
dastrobu
  • 1,600
  • 1
  • 18
  • 32

0 Answers0