Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Should be 2. The <code>main</code> function is static so it doesn't need an object.</p> <p><code>ClassA a</code> is an object and <code>ClassB b</code> is an object</p> <p><strong>EDIT</strong>: ClassB doesn't consist of two objects because extends is an <code>is-a</code> relationship and not a <code>has-a</code> relationship. (ta mik)</p> <p><strong>EDIT</strong>: There is also the <code>String[]</code> object that is created by the runtime system, and potentially any number of string objects place within that array. I am purposefully ignoring these but acknowledge their possible existence. (ta diveshpremdeep and Adam Goode)</p> <p><strong>FINAL EDIT</strong>: In order to determine how many objects are created (by the program, not the runtime system) you can use the <code>javap</code> program on the commandline like so (if test.java contains your example)</p> <pre><code>$ javac test.java $ javap -c ClassB </code></pre> <p>output:</p> <pre><code>Compiled from "test.java" class ClassB extends ClassA{ ClassB(); Code: 0: aload_0 1: invokespecial #1; //Method ClassA."&lt;init&gt;":()V 4: return public static void main(java.lang.String[]); Code: 0: new #2; //class ClassA 3: dup 4: invokespecial #1; //Method ClassA."&lt;init&gt;":()V 7: astore_1 8: new #3; //class ClassB 11: dup 12: invokespecial #4; //Method "&lt;init&gt;":()V 15: astore_2 16: return } </code></pre> <p>As you can see, there are only two bits of bytecode that are <code>new</code> (which creates objects I assume). One for class <code>ClassA</code> and the other for class <code>ClassB</code>. You can note that the <code>invokespecial</code> command is invoked afterwards to call the constructor, and also how class <code>ClassA</code>'s constructor is called from class <code>ClassB</code>'s constructor, but no new object is created inside the constructor (it is the default empty constructor).</p> <p>calling <code>javap -c ClassA</code> shows an equally boring constructor which invokes the constructor for Object.</p> <p>In summary: It is the <code>new</code> bytecode which creates objects on the heap, not the <code>invokespecial</code> which merely fills in the details of the memory allocated by the <code>new</code> bytecode.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload