dumbPotato21
dumbPotato21

Reputation: 5695

Can main and constructor be together in a class in Java

Check The below Code :

import Shashwat.TestJava;

public class Main extends TestJava {

    public static void main(String s[]) {
        System.out.println("Inside Orignal \"Main\" Method");
        Main m = new Main();
    }

    public void Main() {
        System.out.println("Inside Duplicate Main");
    }
}

Now the point is that when I execute the program, This line runs

System.out.println("Inside Orignal \"Main\" Method");

After which I create a Main class Object using

Main = new Main();

As far as I have seen this should call the constructor which has to be named 'Main' for the Class is named Main. Now This is what it executes to

Inside Orignal "Main" Method

But I have created a constructor and it should print text out. So Why is it not printing ? Are Constructors not allowed in a class with a main method ?

Upvotes: 1

Views: 134

Answers (2)

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62864

It's not printing, because you've created a void-returning method with a name Main(), but in order to be a constructor it should rather be:

public Main() {
   System.out.println("Inside Duplicate Main");
}

Upvotes: 8

Eran
Eran

Reputation: 393781

This is not a constructor, it's a regular method :

public void Main()
{
    System.out.println("Inside Duplicate Main");
}

Since your Main class has no constructor, the compiler generates a default constructor and calls it when Main = new Main(); is executed. That's why you don't see "Inside Duplicate Main".

This is a constructor (note there is no return type) :

public Main()
{
    System.out.println("Inside Duplicate Main");
}    

Remove the void from your Main method and you'll see that your constructor is called.

Upvotes: 3

Related Questions