Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create object using of vs new

Tags:

java

lombok

During implementing my task, I saw other developers, they create a class using @AllArgsConstructor(access = AccessLevel.PRIVATE) which made the class constructor private. Then, they create an object using of instead.
What is the difference between create using new and of?

A a = new A();
A a =  A.of();


@AllArgsConstructor(access = AccessLevel.PRIVATE)
@EqualsAndHashCode
public class A
{
    @NonNull
    String data;

    public static A of() 
    {
        return new A();
    }

 }
like image 667
SpringKhmer Avatar asked Mar 21 '26 02:03

SpringKhmer


1 Answers

Over time, it has become clear that, since you don't name parameters on the call, it is difficult to create objects using various methods, if the optional values are of the same type.

One (fairly dumb) example would be a Person class, which might allow specifying just the first name or the last name. In that case, the following constructors wouldn't work:

Person(String firstName, String lastName)

Person(String firstName)

Person(String lastName)

The first one is fine, but the other two are in conflict, and it cannot be resolved, because you cannot name the constructor or the parameter.

Using static factory methods allows naming the methods where necessary:

Person of(String firstName, String lastName)

Person ofFirstName(String firstName)

Person ofLastName(String lastName)

The general of is used when you don't need to name it. It can still be overloaded in the same manner constructors could be overloaded, e.g. you might also have:

Person of(String firstName, String lastName, int age)

Although not used as often for classes, a factory method might also return a subclass, if deemed necessary.

For interfaces, a factory method like that is a nice convenience for instantiating an object implementing the interface, instead of having the factory method in a different class.

Prior to interface static method, the JDK implemented Arrays.asList(...) for creating a list of explicitly given objects. With the introduction of interface static methods to the language, that method is now (also) implemented on the List interface itself as List.of(...).

In addition, they also added convenience methods for Set.of(...) and Map.of(...).

like image 67
Andreas Avatar answered Mar 24 '26 21:03

Andreas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!