Note that there are some explanatory texts on larger screens.

plurals
  1. POWhich arguments for superclass constructor?
    primarykey
    data
    text
    <p>I'm studying a chapter in java related to Inheritance, and i have a few questions.</p> <p>I' have basic understanding how inheritance works ( overriding methods, information hiding, how to use private fields from superclass in a subclass etc ), but i have just one problem and i hope you might help me.</p> <p>When superclass have non default constructor(s) - without parameters, that means that in a subclass i have to create new constructor (it can be default - without parameters ), but in a first statement must be <strong>superclass constructor call</strong>.</p> <p>Ok, so far so good. I understand so far. In subclass you must call superclass constructor, matching any of constructors parameters.</p> <p>But lets check following code: (Superclass)</p> <pre><code>public class Vehicle { private int numOfWheels; private double avgGallonsPerMile; public Vehicle(int numOfWheels, double avgGallonsPerMile) { this.numOfWheels = numOfWheels; this.avgGallonsPerMile = avgGallonsPerMile; } } </code></pre> <p>And another Subclass code: </p> <pre><code>public class Car extends Vehicle{ public Car(double avgGallonsPerMile) { super(What should i write here?, avgGallonsPerMile); //force numOfWheels to 4; } } </code></pre> <p>Here is the exercise for subclass:</p> <p>Each subclass contains a constructor that accepts the miles-per-gallon value as an argument and forces the number of wheels to the appropriate value—2 for a MotorCycle and 4 for a Car.</p> <p>In subclass constructor i don't need <strong>numOfWheels field</strong>, because i will force it to 4 ( for car ) and 2(for motorbike) anyway.</p> <p>But stil i need that data for superclass anyway. Where to get that data? What should as first parameter in call to superclass constructor.</p> <p>But still this isn't the lonely case. I got lots of exercises that i don't need certain data in subclass constructor as parameters, BUT still i need them in superclass constructor call.</p> <p>What should i do in such cases ? </p> <p>I really hope you understood me, what i want to tell. It's kinda difficult.</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.
 

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