Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

Tip of the Day
Language: Java
Expertise: Beginner
Aug 30, 2000



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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 1 constructors. 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;
Deepak Pant
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date