Different instance variables show same value when using get method
I have this piece of code:
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;
}
}
I was told that this program will return the values 2 and 2 but I cannot understand why. According to what I know it should开发者_如何学Go show 1 and 2. Can someone explain or give a link to an explanation? Thank you.
You have declared x as a static member. A static
member is shared by all instances of the same class.
static int x;
This is why the output is 2 and 2
If you want that every instance of the class Base has its own value of the member x, you must remove the static
keyword.
Static means that it belongs to class, not instance, i.e. it shared by all instances of the class.
精彩评论