Customizing constructors and initialization
We want to initialize instances of the Rectangle
class with the width and height values for the new rectangle. In order to do so, we can take advantage of the previously introduced constructors. Constructors are special class methods that are automatically executed when we create an instance of a given type. Java runs the code within the constructor before any other code within a class.
We can define a constructor that receives both the width and height values as arguments, and use it to initialize the fields with the same names. We can define as many constructors as we want to, and therefore, we can provide many different ways of initializing a class. In this case, we just need one constructor.
The following lines create a Rectangle
class and define a constructor within the class body. At this time, we aren't using access modifiers at all because we want to keep the class declaration as simple as possible. We will work with them later. The code...