Так почему же, когда я использую void в объявлении метода конструктора, статическое поле класса больше не изменяется?
Переведено автоматически
Ответ 1
В Java конструктор не является методом. У него есть только имя класса и определенная видимость. Если он объявляет, что возвращает что-то, то это не конструктор, даже если он объявляет, что возвращает a void. Обратите внимание на разницу здесь:
publicclassSomeClass { publicSomeClass() { //constructor } publicvoidSomeClass() { //a method, NOT a constructor } }
Кроме того, если класс не определяет конструктор, компилятор автоматически добавит для вас конструктор по умолчанию.
Ответ 2
public void class1() - это не конструктор, это метод void, имя которого случайно совпадает с именем класса. Он никогда не вызывается. Вместо этого java создает конструктор по умолчанию (поскольку вы его не создавали), который ничего не делает.
Ответ 3
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.
Ответ 4
This is arguably a design flaw in Java.
classMyClass {
// this is a constructor MyClass() {...}
// this is an instance method voidMyClass() {...}
}
Perfectly legal. Probably shouldn't be, but is.
In your example, class1() is never getting called, because it's not a constructor. Instead, the default constructor is getting called.
Suggestion: familiarize yourself with Java naming conventions. Class names should start with uppercase.