Java Interview Question: Can a Constructor in Java have a Return type?


The one-word answer to this question is "no", Java does not allow constructors to have a return type not even void.

Let's take a look at an example:

public class Main {

    int i;

    public void Main() {
        System.out.println("Not considered as a Constructor!!");
    }

    public String Main(int i) {
        System.out.println("Not considered as a Constructor!!");
        return "Hello!";
    }

    public Main() {
        System.out.println("public Main(): Valid Constructor!");
    }

    public Main(int i) {
        System.out.println("public Main(int i): Valid Constructor!");
    }

    public static void main(String[] args) {
        Main main1 = new Main();
        Main main2 = new Main(10);
        main1.Main(); //this is a method call!
    }

}
Output:
public Main(): Valid Constructor!
public Main(int i): Valid Constructor!
Not considered as a Constructor!!

What happens when you specify a return type to a Constructor in Java?

    Well, there will be no errors but it will no longer be a constructor but just another method of a class with a code-smell (a method with a wrong naming convention)

    If you add a return type to Java Constructors they are treated as methods

Why constructs in Java do not allow return types?

    Remember, the purpose of constructors is to initialize objects, and their invocation is implicitly triggered during object creation, allowing return types would blur the distinction between constructors and methods, leading to confusion and potential misuse.

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap