Java "void" and "non void" constructor

I wrote this simple class in java just to test some of its functions.

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); } } 

Output:

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, when I use void in the declaration of the constructor method, the static field of the class no longer changes?

+7
java constructor void
source share
4 answers

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

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

In addition, if the class does not define a constructor, then the compiler will automatically add a default constructor for you.

+30
source share

public void class1 () is not a constructor, it is a void method whose name matches the name of the class. He is never called. Instead, java creates a default constructor (since you did not create one) that does nothing.

+5
source share

Using void in a constructor by definition means that it will no longer be a constructor. The constructor does not have a return type. While void does not return a value in the strict sense of the word, it is still considered the inverse type.

In the second example (where you use void) you will need to do h.class1() to call the method, because it is no longer a constructor. Or you can just remove the void.

+1
source share

This may be a design error in Java.

 class MyClass { // this is a constructor MyClass() {...} // this is an instance method void MyClass() {...} } 

Absolutely legal. Probably should not be, but there is.

In your example, class1 () is never called because it is not a constructor. Instead, the default constructor is called.

Suggestion: Check out the Java naming conventions. Class names must begin with capital letters.

0
source share

All Articles