It can be tedious to initialize all of the variables in a class each time an instance is
created. Even when you add convenience functions like set Dim( ), it would be simpler and more concise to have all of the setup done at the time the object is first created .. Because the requirement for initialization is so common, Java allows objects to initialize themselves when they are created. This automatic, initialization is performed through , the use of a constructor .. A constructor initializes an object immediately upon creation. It has the same name as the class in which it resides arid is syntactically similar to a method. Once defined, e constructor is automatically called immediately after the object is created, before the new operator completes. Constructors look a little strange because they have no return type, not even void. TI$ is because the implicit return type of a class’ Constructor is the class type itself. It is the constructor’s job to initialize the internal state of ‘an object so that the code creating an instance will have a fully initialized . usable object immediately. You can rework the Box example so that the dimensions of a box arc automatically initialized when an object is constructed. To do so, replace set Dim( )with a constructor. Let’s begin by defining a simple constructor that simply sets ‘the dimensions of each box to the same values. This version is shown here.
As you can SL’C, both my box and were initialized by the Box( ) constructor when they were created, Since the constructor elves all boxes the dimension s, 10 by 10 by ,10,both my box l and my box will have the same volume. The statement inside Box() is for the sake of Most constructor functions . will not display anything. They will simply initialize an’ object. . Before moving on, let’s reexamine the new operator. As you know, when you allocate an object, use the following general form: new Box( ) is calling the Box( ) constructor. When you do not explicitly definea constructor for a’ class, then java creates a default constructor for the class. This is why the preceding the of code worked-In earlier versions. of Box that did not define a constructor. The default constructor automatically initializes all instance variables to zero. The default constructor is often sufficient for simple classes, but it usually won’t· do for more sophisticated ones. Once you define your own constructor, the default constructor is no longer used .