Reputation: 89
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 show 1 and 2. Can someone explain or give a link to an explanation? Thank you.
Upvotes: 1
Views: 169
Reputation: 4543
Static means that it belongs to class, not instance, i.e. it shared by all instances of the class.
Upvotes: 1
Reputation: 2437
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.
Upvotes: 4