Updates
  • Starting New Weekday Batch for Java Full Stack Developer on 24th June 2024 @ 02:00 PM to 04:00 PM
  • Starting New Weekend Batch for Java Full Stack Developer on 06th July 2024 @ 11:00 AM to 02:00 PM
  • Starting New Weekday Batch for Java Full Stack Developer on 08th July 2024 @ 04:00 PM to 06:00 PM
  • Starting New Weekday Batch for Java Full Stack Developer on 29th July 2024 @ 10:00 AM to 12:00 PM
Join Course

Constructor

A constructor is a special type of method which is basically used to initialize a class level variable, either that variable is an instance variable or a static variable.

As we have discussed that a constructor is special type of method, so we need to follow few important concepts to define a constructor, and the concepts are: -

• Constructor name must be same as its class name.
• Return type is not allowed in the case of constructor.

o (When we define a constructor with a return type then we do not get any error message at the time of compilation but that constructor behaves like a normal method).

• We can’t invoke a constructor explicitly.

o (Unlike a method, a constructor processes automatically at the time of its class object creation).

• We can define parameters in the constructor as a method.

• When we use a constructor to create an object then we need to remember the following points:

o Numbers of arguments must be the same as the numbers of parameters.
o Types of arguments must be the same as the types of their parameters.
o Sequence of arguments must be the same as the sequence of the parameters.

            
class JTC{
	public static void main(String arg[]){
		A a1 = new A();
	}
}
class A{
	A(){
		System.out.println("constructor in A class");
	}
	void A(){
		System.out.println("It is not a constructor it is a method.");
	}
}
        
    constructor in A class
            

In the above program we have a class which is A and inside the class A we have a constructor A() and we have an instance method which is void A(). In the other class which is JTC we are creating an object of class A using A() class constructor and void A() is not a constructor because we are declaring it along with a void, so it behaves like an instance method. Thus, if you want to invoke that method you have to call it up explicitly like discussed in the chapter of methods.

            
class JTC{
	public static void main(String arg[]){
		Student s1 = new Student(101,"Vivek","vivek@jtcindia.org","Indian");
		Student s2 = new Student(102,"Rahul","rahulraj@jtcindia.org","USA");
		s1.show();
		s2.show();
	}
}
class Student{
	int sid;
	String sname;
	String semail;
	static String snationality;
	
	Student(int id, String name, String email, String nationality){
		sid = id;
		sname = name;
		semail = email;
		snationality = nationality;
	
	}

	void show(){
		System.out.println("----Student Details----");
		System.out.println("sid :- "+sid);
		System.out.println("sname :- "+sname);
		System.out.println("semail :- "+semail);
		System.out.println("snationality :- "+snationality);
	}
}
        
    ----Student Details----
    sid :- 101
    sname :- Vivek
    semail :- vivek@jtcindia.org
    snationality :- USA
    ----Student Details----
    sid :- 102
    sname :- Rahul
    semail :- rahulraj@jtcindia.org
    snationality :- USA
            

In the above program we have a Student class where I have declared a constructor with int, string, string and string type of parameters and we are using this constructor to initialize the class level variables. In Student class we have a static variable with static string snationality, because it is a static variable so it gets only one memory at the time of Student class loading and the same memory will be accessible for all the objects of Student class, that is the reason whatever values which we will be injecting along with last object will be the same value for snationality for all the student class objects. Hence it is best to avoid static variable initialization along with a constructor.

Internal implementation for Constructor: -

As we know after successful compilation, we get a.class file for every class, but there is one important role of the java compiler on every .class file and that is the compiler declares a non-parameterized constructor in every class internally which is called default constructor.

            
class A{
	int a;
	void m1(){}
	public static void main(String arg[]){}
}

        
    C:\Users\JTC\Desktop>javap A
    Compiled from "Test1.java"
    class A {
    int a;
    A();
    void m1();
    public static void main(java.lang.String[]);
    }
            

As we can see in the above example we have a class which is A and inside the A class we have not declared any constructor explicitly; however when we open A.class file on command prompt using javap command, we can see that we get a default constructor. That proves that a java compiler defines a default constructor in every class.

            
class A{
	int a;
	void m1(){}
	A(int a){}
	public static void main(String arg[]){}
}

        
    C:\Users\JTC\Desktop>javap A
    Compiled from "Test1.java"
    class A {
    int a;
    void m1();
    A(int);
    public static void main(java.lang.String[]);
    }
            

In this example we have declared a constructor with int type of parameter in A class and again I am accessing A.class along with javap command and we can see in A class that there is no default constructor created by the java compiler, here we have only one constructor which has been declared explicitly. To conclude we can say that in java the compiler defines a default constructor in a class only while we are not declaring any constructor explicitly, when we define a constructor then the compiler does not declare any default constructor.

Constructor Chaining: -

In Java we can define multiple constructors in a class but the most important thing is that their parameters must be different; it means that we can’t declare more than one constructor with same parameters.

Sometimes we need to invoke more than one constructor for same object as per our business logic, to do so we invoke a constructor from another constructor and the process is called constructor chaining.

In java we can have a statement as (this ()), through which we can invoke a constructor from another constructor in the same class.

When we using this () to implement the constructor chaining process in our program, then we must remember to apply the following rules:

1. This statement (this ()) muse be the first statement inside the constructor.
2. More than one constructor invocation from the same constructor is not allowed.
3. Cyclic constructor invocation is not allowed.

            
class JTC{
	public static void main(String arg[]){
	A a1 = new A(10,20);

	}
}
class A{
	A(){
		System.out.println("no-parametrized constructor in A class");
	}
	A(int a){
		this();
		System.out.println("1-parameterized constructor in A class");
	}
	A(int a, int b){
		this(101);
		System.out.println("2-parameterized constructor in A class");
	}
} 


        
    no-parametrized constructor in A class
    1-parameterized constructor in A class
    2-parameterized constructor in A class
            

In this example we have three constructors in A class and we are using 2-parametrized constructor to create an object of A class but using this (101) we are invoking 1-parametrized constructor from 2-parametrized constructor, also using this () we are invoking default constructor from 1-parametrized constructor. As we know a constructor is a local context so it gets its memory as stack frame in stack area, and in this example first 2-parametrized constructor gets its stack frame then the 1-parametrized constructor gets its stack frame and finally default constructor gets its stack frame. Since stack area works on last-in-first-out concept, so first the default constructor gets executed and thereafter its stack frame gets released, after that 1-paramerized constructor gets executed and finally 2-parametrized constructor gets executed.