user2029261
user2029261

Reputation: 1

Calling overloaded contructor of current class or super class

In java, can a contructor in a class call an overloaded constructor of its superclass (say if we wanted to make that call explicitly and deliberately). I know that a constructor in a class makes implicit call to no-arg default constructor of superclass ( with super (); ) . but suppose I make a call to an overloaded superclass constructor (say super(String s); ) , then my question is, Is this possible? And if this is possible, then is a call to super() still made ahead of super(String s)or not and what are its implications? Also can two constructors from same class one no-arg and one overloaded call each other? Will they be caught in a loop if they do so?

Upvotes: 0

Views: 138

Answers (1)

Bruce
Bruce

Reputation: 1678

You can get the answer in its official tutorial: https://docs.oracle.com/javase/tutorial/java/IandI/super.html

Read this specifically:

The syntax for calling a superclass constructor is

    super();   

or:

    super(parameter list); 

With super(), the superclass no-argument constructor is called. With super(parameter list), the superclass constructor with a matching parameter list is called.

Note: If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error. Object does have such a constructor, so if Object is the only superclass, there is no problem. If a subclass constructor invokes a constructor of its superclass, either explicitly or implicitly, you might think that there will be a whole chain of constructors called, all the way back to the constructor of Object. In fact, this is the case. It is called constructor chaining, and you need to be aware of it when there is a long line of class descent.

So to answer your question: Yes, it is possible, and doable. When you explicitly invoke super constructor with arguments, then only that constructor is invoked.

And, make sure the super constructor invocation is the first line in your constructor, otherwise a compiler error will show.

*****EDITED*****

And, you invoke one specific super class constructor, implicitly or explicit, only. When that superclass constructor is called no other superclass constructors are called, unless it is called within your called superclass constructor. Meanwhile, it is not possible to compile if in the same class multiple constructors call each other recursively - it will be rejected by your compiler.

Hope this helps.

Upvotes: 1

Related Questions