Search code examples
javamainclass

Why does "initializing Test Class" doesn't get print?


Can someone please explain why would TestClass constructor not getting called ? It works if I create an another class but not with the class containing main method ?

public class TestClass {

    public void TestClass(){
        System.out.println("initializing Test Class");
    }


    public static void main(String[] args) {
        TestClass testClass  = new TestClass();

    }

}

Solution

  • What you have created in the class TestClass is NOT a constructor with no argument, but just a method which has got the same name as your class. This is allowed in Java and, in fact, you recon that by the fact that you have added a return type void.
    In your case, when you instantiate the class in the main method, you are actually calling the "default" constructor, which is automatically added by the compiler.
    If you want to see your line printed, you have to remove the "void" clause, so to have a proper constructor with no argument. It should look like this:

    public class TestClass {
    
        public TestClass(){
            System.out.println("initializing Test Class");
        }
    
    
        public static void main(String[] args) {
            TestClass testClass  = new TestClass();
    
        }
    
    }