user697911
user697911

Reputation: 10531

Is this a method or a constructor?

I am reading someone else's code and got confused by this snippet:

public static Builder Builder() {
        return new Builder();
    }

Is this a constructor? Constructor usually has no 'return' statement. Regular method doesn't use the upper case 'Builder()'. I got confused.

Upvotes: 2

Views: 250

Answers (6)

Stephen C
Stephen C

Reputation: 718886

The key feature that distinguishes a constructor from a method is the return type. So

    /* optional modifiers */ Builder()

is a constructor1 for Builder, but

    /* optional modifiers */ Builder Builder()

is a method named Builder that returns a Builder object. It is also an egregious style violation, since Java methods should start with a lower-case letter. Among other things, this makes it easier for human beings to distinguish methods and constructors! (The compiler doesn't care though ...)

There are other telltales too. Some modifiers are allowed for methods, but not for constructors. The static modifier for example.

In short, your example is a method2.


1 - Note that the constructor name must match the enclosing class name. But if you get that wrong the compiler will still call this a constructor ... in the compilation error.

2 - We can further classify it as a static factory method. However, that is a design classification, not anything to do with the Java language itself.

Upvotes: 7

Pallav Kabra
Pallav Kabra

Reputation: 458

It is a method that returns an instance of Builder using no-argument constructor(Default constructor).

Additional to this, below are the Rules for writing Constructor

  1. Constructor(s) of a class must has same name as the class name in which it resides.
  2. A constructor in Java can not be abstract, final, static and Synchronized.
  3. Access modifiers can be used in constructor declaration to control its access i.e which other class can call the constructor.

Upvotes: 0

xingbin
xingbin

Reputation: 28279

No, see jls 8.8

In all other respects, the constructor declaration looks just like a method declaration that has no result (§8.4.5).

....

Unlike methods, a constructor cannot be abstract, static, final, native, strictfp, or synchronized

The method name should be renamed to builder

Upvotes: 1

Raj
Raj

Reputation: 727

its a Static Factory Method, not a constructor.

Upvotes: 0

deHaar
deHaar

Reputation: 18568

It is a method that returns a new instance of Builder using its default constructor Builder().

Upvotes: 0

Nishit
Nishit

Reputation: 1354

A constructor cannot be static, cannot return anything. So, it's a method.

Upvotes: 5

Related Questions