There's various ways to build an object in Java. For my use case let's just assume that I have an abstract Person
class with private attribute fields and a subclass called Tom
.
1. Getters/Setters
A no-arg constructor, setters, and getters in the Person
class. Can be simplified by using Project Lombok's @Data annotation.
Tom tom = new Tom(); // Subclass of Person
tom.setName("Tom");
tom.setAge(42);
I've read that unless working with a framework, this method should be avoided.
2. Parameterized Constructor
Builds the object using constructor parameters. Excessive constructor overloading for big objects with various optional and required attributes. Can also be simplified using Project Lombok's various constructor annotations.
Tom tom = new Tom("Tom", 42);
Then, Tom
's constructor would make a call to super("Tom", 42)
. In Person
, you could make use of constructor overloading if there are many optional parameters.
3. Builder Pattern
Because constructor overloading can get real messy real fast, Josh Bloch presented the Builder Pattern. Again, this can be simplified with Project Lombok's @Builder annotation. This is how it would look with a non-abstract Person
class:
Person person = new Person.Builder().name("Tom").age(42).build();
Trying to use the builder pattern together with inheritance is difficult (but not impossible) as others have said before me.
I'm sure there are many more ways to build an object, but I only listed the ones I am familiar with.
My question is: Using Java 8 or even Java 9 functionality, what is the absolutely best way to build a an object that is a subclass of an abstract superclass with required and optional attributes?
A lot of tutorials and questions on SO are outdated, and probably do not enforce what is considered as best practice nowadays.