英文:
Void in a constructor
问题
Java 14.
class InitByConstructionVoid {
String aux;
public void InitByConstructionVoid() {
this.aux = "aux";
}
}
class InitByConstruction {
String aux;
InitByConstruction() {
this.aux = "aux";
}
}
public class Ex2 {
private String str;
public static void main(String[] args) {
InitByConstruction con = new InitByConstruction();
System.out.println("InitByConstruction: " + con.aux);
InitByConstructionVoid conVoid = new InitByConstructionVoid();
System.out.println("InitByConstructionVoid: " + conVoid.aux);
}
}
**Result:**
InitByConstruction: aux
InitByConstructionVoid: null
关于void
这个词在这里的含义,你能帮我理解一下吗?我的意思是为什么会产生这样的影响。
英文:
Java 14.
class InitByConstructionVoid{
String aux;
public void InitByConstructionVoid(){
this.aux = "aux";
}
}
class InitByConstruction{
String aux;
InitByConstruction(){
this.aux = "aux";
}
}
public class Ex2 {
private String str;
public static void main(String [] args){
InitByConstruction con = new InitByConstruction();
System.out.println("InitByConstruction: " + con.aux);
InitByConstructionVoid conVoid = new InitByConstructionVoid();
System.out.println("InitByConstructionVoid: " + conVoid.aux);
}
}
Result:
InitByConstruction: aux
InitByConstructionVoid: null
Could you help me understand what is the meaning of that word void here? I mean why it influenced like that.
答案1
得分: 1
void
是一种类型。通过将其添加到 InitByConstructionVoid
的签名中,你已经将构造函数降级为普通实例方法。
英文:
void
is a type. By adding it to the signature of InitByConstructionVoid
, you've degraded the constructor to a normal instance method.
答案2
得分: 1
这不是一个构造函数,而是一个同名的方法。
当你使用以下代码时:
InitByConstructionVoid conVoid = new InitByConstructionVoid();
实际上,你正在调用默认构造函数,而这个构造函数并没有被你实现。因此,方法体是空的,并且字段 "aux" 在其中没有被设置。
为了更清楚地说明,尝试使用一个输入参数来编写代码,你会发现你的代码无法编译。
英文:
It is not a constructor, it is a method with the same name.
and when you use this:
InitByConstructionVoid conVoid = new InitByConstructionVoid();
in fact, you are calling the default constructor which is not implemented by you. so the body is empty and the field "aux" is not set in that.
to make it more clear, try to write that with an input and you will see that your code does not compile.
答案3
得分: 0
关键字“void”在任何编程语言中通常表示函数不会有返回类型,所以如果您希望在“InitByConstructionVoid()”函数的范围内获得“aux”的值,请删除void语法。
英文:
The keyword "void" in any programming language usually means that the function will not have a return type, so please erase the void syntax if you are looking to get a value for aux in the scope of your InitByConstructionVoid() function.
答案4
得分: -1
InitByConstruction(){
this.aux = "aux";
}
This should be public for it to be acessible outside the class. Hence the null problem.
英文:
InitByConstruction(){
this.aux = "aux";
}
This should be public for it to be acessible outside the class.Hence the null problem.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论