Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java programming constructor understanding

I'm novice to java and learning my way through it. Is it necessary to have a argument constructor for superclass if subclass have argument constructor, what happens if subclass have argument constructor and superclass have default no-argument constructor?

like image 828
Pravin Agre Avatar asked Jul 14 '26 06:07

Pravin Agre


1 Answers

It would not be a problem - but you can explicitly invoke super() in the constructor of the subclass (as the first statement in the subclass' constructor), or let the compiler do it for you - as it implicitly invokes an argmentless constructor (if one exists) as the first step.

Doing one of these will "let the class know" how to build the super class.

Example:

class A { 
//defaulut argumentless constructor is implicitly created
}

class B extends A {
  B(int x) { 
      super(); //invoking super()
      //rest of construction
  }
}
like image 86
amit Avatar answered Jul 15 '26 18:07

amit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!