java - Is it necessary to add a constructor all the time in child class -


this question has answer here:

i creating child class extending parent class.

my parent class

public class bike {     public int gear, speed;      public bike(int gear, int speed){         this.gear = gear;         this.speed = speed;     }      public void applybreak(int decrement){         speed -= decrement;     }      public void speedup(int increment){         speed += increment;     } } 

my child class

public class mountainbike extends bike {      public mountainbike(int gear, int speed) {         super(gear, speed);         // todo auto-generated constructor stub     }      public static void main(string[] args) {         // todo auto-generated method stub      }  } 

but here in base class if not use constructor throwing error. questions

  1. is necessary add constructor time in child class.
  2. if yes , if no error means.

it pretty simple:

  • each , constructor must call constructor first statement - either within same class, or super class
  • when don't write put constructor in class, java compiler creates empty default constructor calls super()
  • but when super class has no default constructor - won't work

in other words: base class has one constructor taking 2 args. therefore have write down constructor within child class - compiler can't know how create empty constructor calling two-arg super constructor.


Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -