Search code examples
javaconstructorinstanceheap-memory

Java class has only one constructor, no parameter for constructor, all instances of that class will point to the same object in the heap?


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?


Solution

  • 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).