Pravin Agre
Pravin Agre

Reputation: 371

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?

Upvotes: 3

Views: 141

Answers (4)

amit
amit

Reputation: 178411

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
  }
}

Upvotes: 1

Santosh Sidnal
Santosh Sidnal

Reputation: 128

Yes, you can have an argumented/parametrized constructor in child class even you don't have an argumented constructor in parent class. It depends on you what you will do in child class constructor (default/parametrized), whether you can call parents constructor or not.

To call parents constructor use 'super();' at first line in child's constructor. If you pass some parameters to parameters to this super() method then it will try to call parametrized constructor of parent class.

Try to do a round of hands-on on these concepts you will be much more perfect :).

Upvotes: 0

Srinivas B
Srinivas B

Reputation: 1852

No its not necessary to have a argument constructor in super class if subclass contains argument constructor.

Basically, if you create an object for the subclass, the constructors will execute from the super class If parent class has a default constructor. If the super class does not contain any default constructor, the compiler will provide its own default constructor.

Upvotes: 0

Jon Newmuis
Jon Newmuis

Reputation: 26492

In short: each class only needs to worry about instantiating itself.

If the superclass has a no-arg constructor and the subclass does not, then the subclass just does not need to pass any parameters to the superclass constructor; just invoke it. However, if the superclass requires any parameters to instantiate any of its members, then the superclass constructor should indeed accept parameters.

Upvotes: 0

Related Questions