Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <blockquote> <p>I understand that it provides a getter to retrieve both x and y at once in a array instead of a separate getter for each, so the caller will see consistent value, but why private constructor ? what's the trick here?</p> </blockquote> <p>What we want here is chaining of constructor calls to avoid code duplication. Ideally something like this is what we want:</p> <pre><code>public SafePoint(SafePoint p) { int[] values = p.get(); this(values[0], values[1]); } </code></pre> <p>But that won't work because we will get a compiler error:</p> <pre><code>call to this must be first statement in constructor </code></pre> <p>And we can't use this either:</p> <pre><code>public SafePoint(SafePoint p) { this(p.get()[0], p.get()[1]); // alternatively this(p.x, p.y); } </code></pre> <p>Because then we have a condition where the values might have been changed between the call to <code>p.get()</code>.</p> <p>So we want to capture the values from SafePoint and chain to another constructor. That is why we will use the <em>private constructor capture idiom</em> and capture the values in a private constructor and chain to a "real" constructor:</p> <pre><code>private SafePoint(int[] a) { this(a[0], a[1]); } </code></pre> <p>Also note that</p> <pre><code>private SafePoint (int [] a) { this (a[0], a[1]); } </code></pre> <p>does not make any sense outside the class. A 2-D point has two values, not arbitrary values like the array suggests. It has no checks for the length of the array nor that it is not <code>null</code>. It is only used within the class and the caller knows it is safe to call with two values from the array.</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. This table or related slice is empty.
    1. 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