Certain objects can be initialized in many different ways and can also be used in multiple ways. For example, in the Circle class that we all are familiar with, the radius of the circle can be initialized to a specified value or a reasonable default value. Therefore, we can use multiple constructors if there are many instances of fields in a program. Let’s see how we can define two constructors for the Circle class:
public Circle_class() { radius_var1 = 0.54; }
public Circle_class(double radius_var1) { this.radius_var1 = radius_var1;}
We can define as many constructors as we want for a particular class. However, each constructor should have its own parameter list. The Java compiler selects a constructor on its own based on the type of parameters and the number and type of arguments supplied by you.
Calling One Constructor from Another
The ‘this’ keyword as defined above is used specifically in the case a class has multiple constructors. The ‘this’ keyword is then used to invoke one of the other constructors of the same class. In other words, we can rewrite the two previous Circle constructors as follows:
// This is an example of basic constructor: It is used to initialize the radius
public Circle_class(double radius_var1) { this.radius_var1 = radius_var1; } Continue reading JAVA – Defining Multiple Constructors