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( )
//Creating a Constructor
Lets implement this on Eclipse IDE by replacing DimensionsSet( ) method with Box( ) constructor:
1. Launch Eclipse, Ensure that 'Third Project' Java is available, Remove the existing code of Box Class and Declare height, width and depth instance variables in Box class as shown below:
5. Create objects box1 and box2 as instance of Box class, by providing the arguments to be passed during objects creation itself as shown below:
Download the Project:
Click here to download the Project containing the 'Box' and 'Constructor' class files used in this program. (You can download the project and import it to Eclipse IDE on your machine)
Lets implement Box constructor without parameters on Eclipse IDE
1. Launch Eclipse IDE, Create new Java Project 'Project 001', Create Box Class without main( ) method and Declare the instance variables height, width and depth inside the Box class as shown below:
6. Call the volume( ) method and print the results returned by the volume( ) method of Box class and print them as shown below:
Click here to download the project containing the 'Box' and 'ConstructorDemo2' class files used in this program. (You can download this project and import into Eclipse IDE on your machine)
Please comment below to feedback or ask questions.
How to use 'this' keyword will be explained in the next post.