Parameterized constructor can be made by the user if they want to assign some value to instance variable at time of creation of object.
Parameterized constructors are also a good way to perform some operations that are to be performed at the start such as Database connections, pre-checks on values of instance variables or certain operations on static variables.
Some features of parameterized constructor are:
- Default constructor will not be created if parameterized constructor is made by user.
- They can have any access specifier such as private, public or protected.
- Parameterized constructor can be used to initialize instance variables, pre-check on values of instance variables, static variable checks etc.
- Constructors cannot be inherited.
Let us see an example of parameterized constructor.
public class Tech4Humans {
public static void main(String args[]) {
//Creating object using parameterized constructor
A obj = new A(29,"Robert");
obj.printVariables();
// A obj1 = new A();
}
}
class A{
int age;
String name;
//Parameterized Constructor
A(int age, String name){
this.age = age;
this.name = name;
}
void printVariables() {
System.out.println("name = "+name);
System.out.println("age = "+age);
}
}
Output
name = Robert
age = 29
Here we are creating the object using the parameterized constructor. Note here at Line 7. If we uncomment this line then compiler will throw the following error :
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The constructor A() is undefined
at Tech4Humans.main(Tech4Humans.java:7)
This is because we have created a parameterized constructor, so compiler will not create a default constructor, so on calling ‘new A()‘ it threw an error since it cannot find the no-argument constructor.
We can create a no-argument constructor to avoid this error. Please see below code for reference:
public class Tech4Humans {
public static void main(String args[]) {
//Creating object using parameterized constructor
A obj = new A(29,"Robert");
obj.printVariables();
A obj1 = new A();
obj1.printVariables();
}
}
class A{
int age;
String name;
//Parameterized Constructor
A(int age, String name){
this.age = age;
this.name = name;
}
//no-argument Constructor. Constructor Overloading
A(){
this.age = 100;
this.name = "Mona";
}
void printVariables() {
System.out.println("name = "+name);
System.out.println("age = "+age+"\n");
}
}
Output
name = Robert
age = 29
name = Mona
age = 100
The above code is using the concept of overloading. So let us understand about Constructor Overloading.