[英]Can't understand the logic behind output of java program involving static objects
我正在阅读有关静态关键字的信息。 我尝试了一个涉及静态对象的程序。 输出与概念不同。 我不明白为什么我没有得到a20的输出。 虽然a1和b1都在控制台上,但a20不在。 为什么我在输出中两次得到a1?
package j1;
class a {
a(int i) {
System.out.println("a"+1);
}
}
class b {
b(int i) {
System.out.println("b"+1);
}
}
class c {
static a a1=new a(1);
static b b1=new b(1);
c() {
System.out.println("c()");
}
static a a2=new a(20);
}
public class Static {
public static void main(String[] args) {
new c();
}
}
//output:
a1
b1
a1
c()
您的a的构造函数是
a(int i){
System.out.println("a"+1);
}
它只能打印“ a1”,如果要打印“ a20”,则需要将参数i合并到输出中。
也许只是错字。 您正在打印文字而不是参数i
。
System.out.println("a"+1);
那应该是
System.out.println("a"+i);
下面的代码应该有所帮助:
void a(int i) {
System.out.println("a" + i);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.