Understand constructor in 5 minutes

Hi guys! Here we will learn the constructor concept in JAVA. A Constructor is like a method of a class but with the some differences.

It is easy to learn about the constructor concept with the following points.

  • Constructors used for initialization of the values for a JAVA object.
  • Constructor name will be always same as class name and have no return type.
  • Constructors created inside the class body but then after they does not consider as a class member.
  • A Constructor called automatically whenever an instance of an object is created.

Here we have some more stuff about the constructors.

This is the basic syntax to create a constructor.

public ClassName (parameters) [throws exception…]

{

statements…

}

 

In above syntax the public keyword allows to use this constructor by the another classes. Constructor name always will be declare as same as class name and they can throw exception.

As we already mentioned constructor are use for initialization of the value of an object. Lest understand by the way of an example.

Example:

Let suppose we have a class named Student and this class have two member variables student_name and student_id.

Now this is the class structure.

class Student{

private String student_name; //Member Variables
private int student_id;    //Member Variables

public Student(String name, int id)     //Constructor name

{

student_name=name;
student_id=id;

}

}

Explanation: Now the class has been generated with a constructor and at the time of the creation of instance for the object of Student class this constructor will call automatically.

Let see this:

Student obj=new Student(“Harry”, 1001); 

 /* created an object with two parameters which we declare in constructor already */

Now after the compilation of the above line, an object will be created with the passed values.

Remember: If we do not create an object in a class. JVM creates a default constructor automatically with no parameters. It shows the constructor also can implement overloading like methods.
Lest look an example of constructor overloading in JAVA.
class Student{
private String student_name;                                    //Member Variable
private int student_id;                                                //Member Variable
private int student_age;                                           //Member Variable
//First  constructor
public Student(String name, int id)                         //Constructor name
{
student_name=name;
student_id=id;
}

//Second  constructor
public Student(String name, int id, int age)                         //Constructor name
{
student_name=name;
student_id=id;
student_age=age;
}

//default constructor or non parameterized constructor

public student(){
}
}