Java Constructor with Example

May 4, 2014 | Constructors
The constructs (building blocks) of a Java class are variables, constructors, methods and some rarely used static blocks etc. Now let us discuss Java Constructor.

1. What is constructor or features of constructor?

A Java Constructor has the following two features.
  1. A constructor looks like a method but without any return type (even void should not exist).
  2. Constructor name and class name should be the same.

2. Why constructors are required?

Something must be executed at the start of execution of code, without the intervention of a Programmer, then a constructor is required.

3. What are the features or advantages of constructors?

  1. A constructor is called implicitly when an object is created. Incase of method, it should be called explicitly. Forgetting to call, the method is not executed. Regarding constructor, it is assumed practically, atleast one object is created in the code so that the constructor is called.
  2. Mainly used to initialize variables and objects in the code that can be used every method.
  3. A constructor should not be called like a method with an object. To call (or better word is access) the constructor, an object must be created.

4. What is default constructor?

A constructor without any parameters is known as default constructor because it is created and supplied into the program by the JVM if the Programmer does not provide one himself. Default constructor other name if no-args constructor.

5. Can we overload constructor like methods?

Yes, definitely. Like method overloading, constructor overloading (parameterized constructors) is also possible.

Following program uses a default constructor.
public class Student
{
  int marks;                  // variable just declared

  public Student()            // default constructor (does not have parameters)
  {
    marks = 80;               //   variable is initialized (assigned value)
    System.out.println("From constructor");   // just to know whether constructor is called or not
  }
 
  public static void main(String args[])
  {
    Student s1 = new Student();
    Student s2 = new Student();

    System.out.println("From main method: " + s1.marks);
  }
}

Java Constructor Let us see the salient points of the code.

  public Student() 
  {
    marks = 80;  
    System.out.println("From constructor");  
  }

A Student class constructor is created without any parameters, known as default constructor. In the constructor, marks variable is initialized with a value of 80.

Student s1 = new Student(); Student s2 = new Student();

Two objects s1 and s2 are created and thereby two times the constructor is called. Observe the screenshot.

System.out.println("From main method: " + s1.marks);

marks variable is initialized in constructor and called from main() method. Likewise, the marks variable can be called from any method.