In this tutorial we will show you how to use the Constructors in details.
Example code provided here will help you in learning the Java Constructors easily.
While creating a class if any constructor is defined then compiler does not automatically create a default parameter less constructor.
In a class you can define any number of constructors having different parameters. These types of constructor is used when you have to create the object of class with different parameters.
In the following java class Parent.java we are declaring a constructor which takes int as an argument.
Then we showed the use of this.
Here is the complete example code.
/////////////////// class without a parameterless constructor.
// If any constructor is defined, the compiler doesn't
// automatically create a default parameterless constructor.
class Parent {
int _x;
Parent(int x) { // constructor
_x = x;
}
}
////////////////// class that must call super in constructor
class Child extends Parent {
int _y;
Child(int y) { // WRONG, needs explicit call to super.
super(0);
_y = y;
}
}
In the example above, there is no explicit call to a
constructor in the first line of constructor, so the
compiler will insert a call to the parameterless
constructor of the parent, but there is no parameterless
parent constructor! Therefore this produces a compilation error.
The problem can be fixed by changing the Child
class.
////////////////// class that must call super in constructor
class Child extends Parent {
int _y;
Child(int y) { // WRONG, needs explicit call to super.
_y = y;
}
}
Or the Parent class can define a parameterless
constructor.
/////////////////// class without a parameterless constructor.
// If any constructor is defined, the compiler doesn't
// automatically create a default parameterless constructor.
class Parent {
int _x;
Parent(int x) { // constructor with parameter
_x = x;
}
Parent() { // constructor without parameters
_x = 0;
}
}
A better way to define the parameterless constructor is to call the parameterized constructor so that any changes that are made only have to be made in one constructor.
Parent() { // constructor without parameters
this(0);
}
}
Note that each of these constructors implicitly calls
the parameterless constructor for its parent class, etc,
until the Object class is finally reached.