Call Constructor from Constructor Java

Calling Constructor from Constructor requires precautions on usage. Read and understand carefully.

What is a constructor and what is its role in programming?

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 is given using a 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);
  }
}

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 (in Spring, it is known as setter injection; injecting the properties to an object through 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.

Constructors is good concept in Java 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.

Leave a Comment

Your email address will not be published. Required fields are marked *