Consider the following class:
public class Rectangle {
private int length;
private int width;
public Rectangle(int l, int w) {
length = l;
width = w;
}
}
What is the purpose of the constructor in the Rectangle
class?
a) To assign a value to the length
variable
b) To assign a value to the width
variable
c) To create an instance of the Rectangle
class
d) To initialize the length
and width
variables with given values
The correct option is d) To initialize the length
and width
variables with given values.
The purpose of a constructor in a class is to initialize the instance variables of an object. In this case, the constructor Rectangle(int l, int w)
takes two parameters l
and w
, which represent the length and width of the rectangle, respectively. The constructor then assigns these parameter values to the length
and width
instance variables of the Rectangle
object being created.
By initializing the length
and width
variables with the given values in the constructor, we ensure that every Rectangle
object created has its length and width set to specific values. This allows the object to be used consistently throughout the program by accessing its properties using getter and setter methods or other member functions.