Question:
Consider the following classes in Java:
public class Rectangle {
private int width;
private int height;
public Rectangle(int width, int height) {
this.width = width;
this.height = height;
}
public int getArea() {
return width * height;
}
public void setWidth(int width) {
this.width = width;
}
public void setHeight(int height) {
this.height = height;
}
}
public class Square extends Rectangle {
public Square(int sideLength) {
super(sideLength, sideLength);
}
public void setSideLength(int sideLength) {
setWidth(sideLength);
setHeight(sideLength);
}
}
Explain whether the class hierarchy demonstrated in the code snippet above adheres to the principles of Object-Oriented Programming (OOP). Analyze its design, inheritance, and relationships between classes.
Answer:
The class hierarchy demonstrated in the code snippet adheres to the principles of Object-Oriented Programming (OOP). Here's a detailed analysis of its design, inheritance, and relationships between classes:
The design of the classes Rectangle
and Square
follows the principle of encapsulation by declaring the width
and height
fields as private
and providing public
methods to access and modify these fields.
The Rectangle
class has a constructor method that accepts the width
and height
as parameters and initializes the corresponding fields.
The Rectangle
class also has a getArea
method, which calculates and returns the area of the rectangle based on its width and height.
The Square
class is a subclass of Rectangle
and inherits its fields and methods. It adds an additional method setSideLength
specific to a square.
The Square
class inherits from the Rectangle
class using the extends
keyword. This relationship represents the "is-a" relationship between a square and a rectangle - a square is a specific type of rectangle where all sides are equal.
The Square
class overrides the setWidth
and setHeight
methods inherited from the Rectangle
class in order to maintain the square's invariant (all sides are equal). It accomplishes this by setting both the width and height to the given value in the setSideLength
method.
Note that the Square
class does not declare any new fields or methods. It inherits them from the Rectangle
class.
The relationship between the Rectangle
and Square
classes can be described as superclass-subclass relationship or parent-child relationship. The Square
class is a specialized version of the Rectangle
class, inheriting its properties and behaviors.
The Square
class utilizes the methods from the Rectangle
class to set the width and height, maintaining the square's invariant. This relationship demonstrates the principle of code reuse, as the Square
class can use the existing methods from the Rectangle
class without having to implement them again.
Overall, the class hierarchy demonstrated in the code snippet follows the principles of OOP by encapsulating data, utilizing inheritance, and establishing relationships between classes to model real-world concepts.