java "void" and "non void" constructor

In Java, the constructor is not a method. It only has the name of the class and a specific visibility. If it declares that returns something, then it is not a constructor, not even if it declares that returns a void. Note the difference here:

public class SomeClass {
    public SomeClass() {
        //constructor
    }
    public void SomeClass() {
        //a method, NOT a constructor
    }
}

Also, if a class doesn't define a constructor, then the compiler will automatically add a default constructor for you.


public void class1() is not a constructor, it is a void method whose name happens to match the class name. It is never called. Instead java creates a default constructor (since you have not created one), which does nothing.


Using void in the constructor by definition leads it to not longer be the constructor. The constructor specifically has no return type. While void doesn't return a value in the strictest sense of the word, it is still considered a return type.

In the second example (where you use the void), you would have to do h.class1() for the method to get called because it is no longer the constructor. Or you could just remove the void.