Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<pre><code>public DM(Euro a){ </code></pre> <p><code>a</code> isn't a "new" object. When the rest of the program uses this constructor, it will need to have an <em>existing</em> <code>Euro</code> object, like this:</p> <pre><code>Euro someEuroVariable; // for example ... DM d = new DM(someEuroVariable); </code></pre> <p>and the constructor will then use <code>someEuroVariable</code> as its parameter, which it refers to as <code>a</code>. But no new <code>Euro</code> object is created by this.</p> <p>Hope this helps.</p> <p><b>EDIT:</b> To answer the question in the comments: You can't say </p> <pre><code>DM d = new DM(); </code></pre> <p>because <code>DM</code> doesn't have a constructor that you can use with no parameters. But let's say you used a legal constructor like</p> <pre><code>DM d = new DM(1.234); </code></pre> <p>and now you say</p> <pre><code>Euro a = d; </code></pre> <p><code>a</code> and <code>d</code> will be references to the <em>same</em> object. This object has a <em>run-time</em> type of <code>DM</code>. When you declare a variable <code>a</code> to have type <code>Euro</code>, that means that <code>a</code> can, during its lifetime, be an object of type <code>Euro</code> <em>or any of its subclasses</em>. However, since the compiler can't tell what the actual type will be at runtime, you can only use a method <code>a.method()</code> if the method was defined for <code>Euro</code>. If <code>DM</code> has a new method <code>method2</code> that <code>Euro</code> doesn't have, you can't call it directly with <code>a.method2()</code>. It also means that later on, you could reassign <code>a</code> to an object with some other subclass:</p> <pre><code>a = new Lira(100000000000.0); </code></pre> <p>while you can't do that with <code>d</code> because it can only be of type <code>DM</code> or a subclass of <code>DM</code>:</p> <pre><code>d = new Lira(100000000000.0); // Error at compile time </code></pre> <p>This distinction between compile-time type and run-time type can be difficult to grasp until you get used to it. It's also totally unrelated to what happens when you pass a <code>Euro</code> as a parameter to a <code>DM</code> constructor; the object that you pass as a parameter is a separate object and must exist before the constructor is called.</p>
 

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