1

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.

2

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Static means that it belongs to class, not instance, i.e. it shared by all instances of the class.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.