Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Because constructing your subclass object may be done in a different way from how your superclass is constructed. You may not want clients of the subclass to be able to call certain constructors available in the superclass. </p> <p>A silly example:</p> <pre><code>class Super { protected final Number value; public Super(Number value){ this.value = value; } } class Sub { public Sub(){ super(Integer.valueOf(0)); } void doSomeStuff(){ // We know this.value is an Integer, so it's safe to cast. doSomethingWithAnInteger((Integer)this.value); } } // Client code: Sub s = new Sub(Long.valueOf(666L)): // Devilish invocation of Super constructor! s.doSomeStuff(); // throws ClassCastException </code></pre> <p>Or even simpler:</p> <pre><code>class Super { private final String msg; Super(String msg){ if (msg == null) throw new NullPointerException(); this.msg = msg; } } class Sub { private final String detail; Sub(String msg, String detail){ super(msg); if (detail == null) throw new NullPointerException(); this.detail = detail; } void print(){ // detail is never null, so this method won't fail System.out.println(detail.concat(": ").concat(msg)); } } // Client code: Sub s = new Sub("message"); // Calling Super constructor - detail is never initialized! s.print(); // throws NullPointerException </code></pre> <p>From this example, you see that you'd need some way of declaring that "I want to inherit these constructors" or "I want to inherit all constructors except for these", and then you'd also have to specify a default constructor inheritance preference just in case someone adds a new constructor in the superclass... or you could just require that you repeat the constructors from the superclass if you want to "inherit" them, which arguably is the more obvious way of doing it. </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.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    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