Constructors in JAVA


AutomationChinnu

It can be tedious to initialize all the variable in a class each time an object is created. Even when you add convenience methods like DimensionsSet( ) as explained in the second example of previous post Post#73, it would be simpler and more concise to have all the setup done at the time object is first created. Java allows objects to initialize themselves through the use of constructor as follows:

Box box1 = new Box(10,10,10);  //Arguments can be passed while creating the object

Constructor is nothing but a method having the same name as the Class. So in order to create a constructor inside Box Class, we have to create a method with the same name of Class i.e. Box( )

Example

Class Box
{
//Creating a Constructor
Box( )
{

}

}

Lets implement this on Eclipse IDE by replacing DimensionsSet( ) method with Box( ) constructor:

1…

View original post 462 more words

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s