SCJP Certification

Sun Certified Java Programmer Certification exam essentials

September 19th, 2009

What is constructor overloadng?

Java Facts, by Daisy Williams.

Constructor overloading is a methodology that allows a class can have any number of constructors that differ in parameter lists. A constructor initialize’s the new object’s state by using its arguments. The compiler differentiates these constructors by taking into account the number of parameters in the list and their types. Constructors are not members of a class, so they are not inherited by subclasses. Therefore, each of the subclasses must specifically implement any constructors it needs. However, a subclass can use the constructors of its superclass by using the super keyword.

The following code describes how constructor overloading works:

class ABC{
ABC(){
System.out.print(“ABC “);
}
ABC(String value){
this();
System.out.print(“abc ” + value);
}
}
public class XYZ extends ABC
{
XYZ(){
System.out.print(“XYZ “);
}
XYZ(String value){
this();
System.out.print(“xyz ” + value);
}
public static void main(String[] args){
new XYZ(“value “);
}
}

A constructor is always invoked when a new object is created. Each superclass in an object’s inheritance tree will have a constructor called. Here the constructors execute as follows:

  1. The constructor calls its superclass constructor, which calls its superclass constructor, and so on all the way up to the Object constructor.
  2. The Object constructor executes and then returns to the calling constructor, which runs to completion and then returns to its calling constructor, and so on back down to completion of the constructor of the actual instance being created.

A constructor is invoked when a new object is created, the constructor calls its superclass constructor, which calls its superclass constructor and so on all the way up to the Object constructor and hence the output is ABC XYZ xyz value.

Share

Back Top

Responses to “What is constructor overloadng?”

Comments (0) Trackbacks (0) Leave a comment Trackback url
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Your email address will not be published. Required fields are marked *

*