Вопрос-ответ

java "void" and "non void" constructor

конструктор java "void" и "non void"

Я написал этот простой класс на java только для тестирования некоторых его функций.

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

Вывод следующий:


2


Но в этом коде:

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

Вывод этого кода:


0


Так почему же, когда я использую void в объявлении метода конструктора, статическое поле класса больше не изменяется?

Переведено автоматически
Ответ 1

В Java конструктор не является методом. У него есть только имя класса и определенная видимость. Если он объявляет, что возвращает что-то, то это не конструктор, даже если он объявляет, что возвращает a void. Обратите внимание на разницу здесь:

public class SomeClass {
public SomeClass() {
//constructor
}
public void SomeClass() {
//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.

class MyClass {

// this is a constructor
MyClass() {...}

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

}

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.

2023-07-06 13:34 java