devxlogo

Call One Constructor from Another Constructor

Call One Constructor from Another Constructor

Constructor is a special kind of method which gets called automatically whenever the object is created. One class can have zero, 1 or more then 1constructors. Basically, you can overload constructor method.

Now that you can have more then one constructor, you may want to reuse the code that you write in different constructor methods. Java provides you a mechanism by which you can call one constructor method from another. The way you achieve this is that the first statement of one constructor should call another constructor using the “this” object reference.

Here is a sample code which shows the technique of calling one constructor from another.

 class MyClass{   // default constructor    public MyClass()    {	this("", 0);    }

Another constructor:

     public MyClass(String strSomeName, int intSomeAge)    {	this.strName = strSomeName;	this.intAge = intSomeAge;    }

Private member variables:

 private String strName;    private int intAge;}

See also  10 Best Apps to Help You Read More Books in Less Time
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist