What is Java Constructor?


Java constructor plays a very important role in coding. Simply a constructor looks like method but is very different from method and purpose. Following tutorial gives complete authority over Java constructors. First let us know where exactly constructors fit in Java coding.

A constructor is that one which is called implicitly when an object is created in Java. A constructor gives properties to an object while it is being created itself. Else, separate methods are required to give properties to the object after it is created. Both styles are given hereunder.

Observe the code where properties for a Student object are given using a Java constructor at the time of object creation.

public class Student
{
  int marks;
  String name;
  public Student(int marks, String name)
  {
    this.marks = marks;
    this.name = name;
  }   
  public static void main(String args[])
  {   
    Student std1 = new Student(50, "Jyostna");  // while std1 is being created, marks and name are given
    System.out.println(std1.marks + " : " + std1.name);
  }
}

public Student(int marks, String name)

This is called constructor and will be discussed downside.

Through constructor, std1 object is given properties of marks and name (in Spring, it is known as constructor injection; injecting the properties to an object through constructor).

Let us repeat the same code with methods, say setter methods.

public class Student
{
  int marks;
  String name;
  public void setMarks(int marks)
  {
    this.marks = marks;
  }
  public void setName(String name)
  {
    this.name = name;
  }
  public static void main(String args[])
  {   
    Student std1 = new Student();   // first object is created
    std1.setMarks(50);         // then properties are assgined
    std1.setName("Jyostna");
    System.out.println(std1.marks + " : " + std1.name);
  }
}

See how much code increases with methods. This is the importance of constructor in Java. In Java, String constructor is overloaded many folds and is discussed in Java String Constructors.

Java Constructor is a good concept and must be studied elaborately; should be known how to write a constructor, constructor overloading, calling same class constructor and super class constructor etc. and all are discussed very clearly with code examples in Constructors and Constructor overloading.

Other Constructor related Topics, Read only when you are comfortable with basic constructor examples

Leave a Comment

Your email address will not be published.