Call Constructor from Constructor Java

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.

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).

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 Reply

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