Is this a method or a constructor?

user697911 :

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.

Stephen C :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=110833&siteId=1