Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


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

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.

 

 

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