-3

Have the following case:

 class Bond {
    private static int price = 5;
    public boolean sell() {
     if(price<10) {
       price++;
       return true;
     } else if(price>=10) {
       return false;
     }

     return false;
    }
    public static void main(String[] cash) {
     new Bond().sell();
     new Bond().sell();
     new Bond().sell();

     System.out.print(price);

     Bond bond1=new Bond();

     System.out.print(price);
    }
 }

It will print: 8 9. Will all instances that will be made, will point to the same object in the heap?

RDK
  • 144
  • 1
  • 1
  • 9
edy12
  • 7
  • 2
  • 1
    why ... do you think that? You think that in order to create a second instance/object, you'll need a second constructor? – Stultuske Jun 08 '21 at 11:40
  • 6
    That behaviour has nothing to do with the constructor, but with the fact that you declared the price field as `static`. See: [What does the 'static' keyword do in a class?](https://stackoverflow.com/questions/413898/what-does-the-static-keyword-do-in-a-class) – OH GOD SPIDERS Jun 08 '21 at 11:40
  • 3
    *"It will print: 8 9"* - No it won't. Did you test and observe your code before asking? – David Jun 08 '21 at 11:44

2 Answers2

4

There's a very simple rule in Java: new SomethingOrOther() will always create a new object (unless it somehow produces an exception).

So the answer is obviously: no, the main method you posted will create 4 instances of Bond.

Those instances happen to not have any fields that makes them different in any interesting way, but they are distinct instances.

The reason it "looks like" only one instance exists is that your price field is static, which means it belongs to the class Bond itself and not to an individual instance, which also means there's only one price ever, no matter how many instances you have (yes, even if there are no instances at all).

Tom
  • 16,842
  • 17
  • 45
  • 54
Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
0

Remove static keyword of "price" to answer it yourself.

static variables hold the same value across all the object instances.

Dinesh Babu
  • 73
  • 1
  • 1
  • 7