Method Named Like Its Enclosing Class

ID

java.method_named_like_class

Severity

low

Remediation Complexity

medium

Remediation Risk

low

Remediation Effort

medium

Resource

Code Smell

Language

Java

Tags

code-style, naming

Description

Reports methods whose name matches the enclosing class name but that are not constructors (they have a return type).

Rationale

In Java, a constructor has the same name as its class and no return type. A method that shares the class name but declares a return type is almost certainly a mistyped constructor: the developer accidentally added a return type, so the method is never invoked during object construction.

public class Widget {
    // Intended as constructor but has return type - this is a regular method
    public void Widget(int size) {
        this.size = size;
    }
}

Remediation

Remove the return type to make it a proper constructor, or rename the method:

public class Widget {
    // Correct constructor - no return type
    public Widget(int size) {
        this.size = size;
    }
}