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.
You have declared x as a static member. A
staticmember is shared by all instances of the same class.This is why the output is
2 and 2If you want that every instance of the class Base has its own value of the member x, you must remove the
statickeyword.