我有这段代码:
class Test {
public static void main (String[] args){
Base b1, b2;
b1= new Base(1);
b2= new Base(2);
System.out.println(b1.getX());
System.out.println(b2.getX());
}
}
public class Base {
static int x;
public Base(){
x=7;
}
public Base( int bM) {
x=bM;
}
public int getX() {
return x;
}
}
有人告诉我这个程序将返回值2和2,但我不明白为什么。根据我所知,它应该显示1和2.有人可以解释或给出一个解释的链接?谢谢。
答案 0 :(得分:4)
您已将x声明为静态成员。 static
成员由同一类的所有实例共享。
static int x;
这就是输出为2 and 2
的原因
如果您希望类Base的每个实例都有自己的成员x值,则必须删除static
关键字。
答案 1 :(得分:1)
静态表示它属于类,而不是实例,即它由类的所有实例共享。