2

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.

user697911
  • 10,043
  • 25
  • 95
  • 169

6 Answers6

7

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.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
5

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

Nishit
  • 1,276
  • 2
  • 11
  • 25
1

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

xingbin
  • 27,410
  • 9
  • 53
  • 103
0

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

deHaar
  • 17,687
  • 10
  • 38
  • 51
0

its a Static Factory Method, not a constructor.

Raj
  • 707
  • 6
  • 23
0

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.
Pallav Kabra
  • 418
  • 3
  • 7