Search code examples
javaconstructorvoid

java "void" and "non void" constructor


I wrote this simple class in java just for testing some of its features.

public class class1 {
    public static Integer value=0;
    public class1() {
       da();
    }
    public int da() {
        class1.value=class1.value+1;
        return 5;
    }
    public static void main(String[] args) {
       class1 h  = new class1();
       class1 h2 = new class1();
       System.out.println(class1.value);
    }
}

The output is:

2

But in this code:

public class class1 {
    public static Integer value=0;
    public void class1() {
        da();
    }
    public int da() {
        class1.value=class1.value+1;
        return 5;
    }
    public static void main(String[] args) {
        class1 h  = new class1();
        class1 h2 = new class1();
        System.out.println(class1.value);
    }
}

The output of this code is:

0

So why doesn't, when I use void in the constructor method declaration, the static field of the class doesn't change any more?


Solution

  • 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.