Question:
Consider the following code snippet:
public class Rectangle {
private int width;
private int height;
public Rectangle(int w, int h) {
width = w;
height = h;
}
public void setWidth(int w) {
width = w;
}
public void setHeight(int h) {
height = h;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public int getArea() {
return width * height;
}
}
a) Explain what is meant by instance variables and how they differ from local variables.
b) Explain what is meant by methods in the context of a class and how they can access and modify instance variables.
c) Write a code snippet that demonstrates how to create an object of the Rectangle class and use its methods to modify its instance variables and calculate and print the area of the rectangle.
Answer:
a) Instance variables, also known as member variables, are variables declared inside a class but outside any method or constructor. Each object of the class has its own set of instance variables. These variables hold data specific to each object and are initialized with default values when the object is created. Instance variables can be accessed and modified by any method or constructor within the class. Unlike local variables, instance variables have default values and exist as long as the object of the class exists.
b) Methods in the context of a class are functions defined within the class that perform specific tasks. They can access and modify instance variables of the class. Methods are declared with a return type, optional parameters, and contain a block of code. They allow the class to encapsulate functionality and provide a way to interact with the objects of the class. Instance variables can be accessed directly within the methods without the need for any special qualifiers.
c) Here is a code snippet that demonstrates how to create an object of the Rectangle class, modify its instance variables using methods, and calculate and print the area of the rectangle:
public class Main {
public static void main(String[] args) {
Rectangle rectangle = new Rectangle(5, 7);
System.out.println("Initial width: " + rectangle.getWidth());
System.out.println("Initial height: " + rectangle.getHeight());
rectangle.setWidth(8);
rectangle.setHeight(10);
System.out.println("Modified width: " + rectangle.getWidth());
System.out.println("Modified height: " + rectangle.getHeight());
int area = rectangle.getArea();
System.out.println("Area of the rectangle: " + area);
}
}
Output:
Initial width: 5
Initial height: 7
Modified width: 8
Modified height: 10
Area of the rectangle: 80
In this code snippet, we first create an object of the Rectangle class with initial width 5 and height 7. We then use the setWidth()
and setHeight()
methods to modify the width and height of the rectangle to 8 and 10, respectively. Finally, we use the getArea()
method to calculate the area of the rectangle and print the result.