Reputation: 10531
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
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
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
Upvotes: 0
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
Reputation: 18568
It is a method that returns a new instance of Builder
using its default constructor Builder()
.
Upvotes: 0
Reputation: 1354
A constructor cannot be static, cannot return anything. So, it's a method.
Upvotes: 5