Hello,
We all know that Java is an Object Oriented Programming.
Meaning, Java works with objects. In this post, we are going to discuss about
construction of Java objects. Yes, objects can be constructed using Constructors of a
Java class. Constructors will make sure that all the variables / members of
current class and its super class are initialized properly.
Constructor
Constructors are the code that runs whenever we use new keyword. A constructor is more like
a normal method in a Java class but with special rules for a special purpose.
Here are the basic ground rules one should follow while
working with Constructors in a Java class.
- Constructor name MUST match the name of the class.
- Constructor MUST NOT have a return type.
- Constructor can have ANY access modifier. To know more about access modifier read this.
- If we don’t define any constructor in a Java class, the compiler will automatically provide us a default constructor. Default constructor will always be NO ARGUMENT constructor.
- Constructors can be OVERLOADED. If we define either no-argument or overloaded constructor, then the compiler will NOT provide any default constructor.
- Constructors can NEVER be OVER-RIDDEN.
- The first statement of any constructor MUST be this or super. If we don’t write it, compiler will insert the first statement for us.
- We can invoke a constructor ONLY in 2 ways.
i. While creating an object
ii. From another constructor
Let us see in detail about the constructor and its special rules. A basic constructor is as follows,
public class ConstructorDemo
{
public static void main(String... strings)
{
// create an object of ConstructorDemo class
ConstructorDemo cDemo = new ConstructorDemo(); // O.K.
// below code doesnt compile.
ConstructorDemo cDemo1 = new ConstructorDemo(1,2); // ERROR.!
}
}
A normal java class appear
as shown above. Observe that I didn't define any constructor in the ConstructorDemo
class and I am trying to create an object using no argument constructor and
also using a constructor which takes 2 integers.
Creating an object with no
argument constructor is O.K. coz, if we didn't define any constructor in the
class the compiler will provide a default no argument constructor. It looks like,
//default constructor
public ConstructorDemo()
{
super();
}
We can see that the constructor
provided by compiler,
- doesn't have any arguments.
- doesn't have a return type.
- has same name as Class name.
- gets the same access modifier as the class. Read Java Access Modifiers to know more about modifiers.
- No code will be provided inside the compiler provided constructor except super() method call. This super() invokes the parent class no-argument constructor. In our case, ContructorDemo is not extending any class. So by default every class extends Object class. Hence the super() method invokes NO ARGUMENT constructor of Object class.
But when I try to create
an object with overloaded constructor, I get a compile time error saying,
The constructor ConstructorDemo(int,
int) is undefined
It is correct. We haven’t
defined a constructor which takes 2 integers. Compiler will ONLY provide us NO
ARGUMENT constructor. For overloaded constructors, we have to define ourselves
or else we get a compile time error.
Now see this below code,
public class ConstructorDemo
{
// overloaded constructor
public ConstructorDemo(int a, int b)
{
// if we don’t write super(), compiler will add for us
super();
// set a and b values to instance variables
}
public static void main(String... strings)
{
// create an object of ConstructorDemo class
ConstructorDemo cDemo = new ConstructorDemo(); // ERROR.!
// below code doesnt compile.
ConstructorDemo cDemo1 = new ConstructorDemo(1,2); // O.K.
}
}
You can see that I have
defined an over-loaded constructor which takes 2 integers. When I try to
compile this class, I get an error at line 16 saying,
The constructor ConstructorDemo() is
undefined
Why is it so? Ideally if
we don’t define any constructor, compiler provides no-argument constructor. BUT
if we define any constructor in the class, then the compiler WON’T provide us
any constructor. In the above example, I have defined an overloaded
constructor. So compiler will not provide no-argument constructor. Hence we get
compile time error saying constructor is undefined.
this & super
this and super are
keywords in Java, so we cannot use them as variables. The purpose of both the
keywords is same. Only difference is,
this – always refers to the current class object
super – always referes to the super class object (parent)
These 2 keywords are
also used for calling the constructors.
this() – calls other constructor in the same class.
super() – calls the constructor in the super (parent) class.
Both the methods this() and super() can be overloaded to call the overloaded constructors.
One rule you should burn
in your head is, constructor calling should be the very first statement in the
constructors. We canNOT use both this()
and super() in a constructor.
If we invoke super()
method, then we canNOT use this() in that constructor. If we invoke this() in
the first statement, then we canNOT use super() in that constructor.
See the below code for
better understanding.
public class ConstructorDemo {
// no-arg constructor
public ConstructorDemo()
{
super(); // invokes the super class no-arg constructor
System.out.println("In NO argument constructor.");
}
// overloaded constructor
public ConstructorDemo(int a)
{
// should be the very first statement
this(); // invokes no-arg constructor of current class
System.out.println("In 1 argument constructor.");
}
// overloaded constructor
public ConstructorDemo(String str , int a)
{
// should be the very first statement
this(a); // invokes one integer argument constructor of current class
System.out.println("In 2 argument constructor.");
}
public static void main(String... strings)
{
// create an object of ConstructorDemo class
System.out.println("Create object using No argument Constructor.");
ConstructorDemo cDemo = new ConstructorDemo();
System.out.println();
System.out.println("Create object using 1 argument Constructor.");
ConstructorDemo cDemo1 = new ConstructorDemo(10);
System.out.println();
System.out.println("Create object using 2 argument Constructor.");
ConstructorDemo cDemo2 = new ConstructorDemo("Number", 20);
}
}
The above program is self-explanatory.
I have defined 3 constructors, no-argument constructor and 2 overloaded
constructor.
Line 37 invokes one integer
argument type constructor which again invokes no–argument constructor type and
it invokes super class no-argument constructor.
Line 41 invokes 2 argument type
constructor which invokes one integer argument constructor which again invokes no–argument
constructor type which again invokes super class no-argument constructor.
That’s how the chain goes. A call
to this() just means we are delaying the call to super class constructor. At
the end of the chain, some constructor must make the call to super class
constructor..!
When I compile and run the above
program, I get the below output,
Create object using No argument Constructor. In NO argument constructor. Create object using 1 argument Constructor. In NO argument constructor. In 1 argument constructor. Create object using 2 argument Constructor. In NO argument constructor. In 1 argument constructor. In 2 argument constructor.
We have seen how an
overloaded constructor can be called using this(). Now lets us how an
overloaded super class constructor can be called.
public class ConstructorDemo extends SuperClass
{
// constructor
public ConstructorDemo()
{
System.out.println("Child class - no argument constructor");
}
public static void main(String... strings)
{
// create an object of ConstructorDemo class
System.out.println("Create object using No argument Constructor.");
ConstructorDemo cDemo = new ConstructorDemo();
}
}
class SuperClass
{
// constructor
public SuperClass()
{
System.out.println("Super class - no argument constructor");
}
}
See the above program,
ConstructorDemo extends
SuperClass
SuperClass extends Object
When I compile and ran
the program, I get the below output,
Create object using No argument Constructor. Super class - no argument constructor Child class - no argument constructor
Observe that I haven’t placed
any super() statement in ConstructorDemo constructor. But still the control has
gone to SuperClass default method. Coz the compiler has places super()
statement for us.
Things get much more interesting
when the super class doesn't have a default constructor.
public class ConstructorDemo extends SuperClass
{
// constructor
public ConstructorDemo(int a, int b)
{
//super(); -- ERROR.! SuperClass doesn't have no-argument constructor
super(a, b); // O.K.
System.out.println("Child class - 2 argument constructor");
}
public static void main(String... strings)
{
// create an object of ConstructorDemo class
System.out.println("Create object using 2 argument Constructor.");
ConstructorDemo cDemo = new ConstructorDemo(10, 20);
}
}
class SuperClass
{
int a;
int b;
// constructor
public SuperClass(int i1, int i2)
{
super(); // no-argument constructor of Object class
System.out.println("Super class - 2 argument constructor");
}
}
In the above program, in
SuperClass you can see that I haven’t defined any no-argument constructor.
As I have defined a 2
argument constructor in the super class, compiler will NOT provide us a
no-argument constructor.
Hence we have to
explicitly call the super constructors from the child class constructors using
the super().
See the 2 argument
constructor of ConstructorDemo class. I tried calling the super constructor
using super() with no arguments and I get an error saying,
The constructor
SuperClass() is undefined
It is correct, coz we
have defined 2 argument constructor in the super class, hence we need to explicitly
call it from the child class.
Below is the output I
get when I try to compile and run the above program.
Create object using 2 argument Constructor. Super class - 2 argument constructor Child class - 2 argument constructor
Here
comes the very BIG question.
Q) - Why
super class constructor gets called when we try to create an object of the
child class?
A) Because
the call to the super class constructor will ensure that when a constructor is
invoked, it can rely on all the fields / instance members in its superclass
being initialised.
When
we create an object of a class, using that object we are free to use parent
class members. To make the parent class variables available to the child class
object, the super() call will make
sure that super class variables are initialised and are ready to use by the
child class object.
That
is the reason super class constructor call is mandatory at the time of object
creation.
Thanks :)
Thanks :)


