java "void";和“非无效"构造函数 [英] java "void" and "non void" constructor
问题描述
我用 java 编写了这个简单的类只是为了测试它的一些功能.
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);
}
}
输出为:
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
时,类的静态字段不再改变?
So why doesn't, when I use void
in the constructor method declaration, the static field of the class doesn't change any more?
推荐答案
在 Java 中,构造函数不是方法.它只有类的名称和特定的可见性.如果它声明返回一些东西,那么它不是构造函数,即使它声明返回一个void
.注意这里的区别:
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.
这篇关于java "void";和“非无效"构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!