1

As in the below program, i instantiated an Store object in the Book class member field. Is this command allocates memory inside every Book class object space in heap or once in a free area of heap and assign the address to it ?

public class Book{

private String bookName;
private Store count = new Store(10);



public Book(String bookName ) { 
    this.bookName = bookName;
}


public void display(){

    System.out.println(this.bookName);
}


public static void main(String[] args) {

    Book main = new Book("Machines");       
    main.display();
    System.out.println(main.count.bookCount);
}

}

user2357112
  • 260,549
  • 28
  • 431
  • 505
Gobi
  • 77
  • 3
  • 10

2 Answers2

0

Since each instance of the Book class contains their own Store class, this allocates memory for each instance rather than as one heap. If you want to use the same Store instance for every Book instance, you must pass the Store instance into the Book class in the constructor like this

public class Book{

private String bookName;
private Store count;



public Book(String bookName, Store count) { 
    this.bookName = bookName;
    this.count = count;
}
Peake
  • 85
  • 1
  • 6
0

Store is a reference type. When you instantiate a reference type, a part of unused heap is allocated to store the actual instance. Then, there will be a "reference" that is stored wherever you currently are. This reference "points" to where the actual object is stored.

Therefore,

The actual Store object is stored somewhere else, not inside the Book instance. In the book instance, a value is changed to the memory address where the Store object is stored at.

Sweeper
  • 213,210
  • 22
  • 193
  • 313