Untitled
java
a month ago
1.7 kB
4
Indexable
Never
// Step 1: Create the Shape interface public interface Shape { double calculateArea(); } // Step 2: Implement the RectangleAdapter class public class RectangleAdapter implements Shape { private Square square; public RectangleAdapter(Square square) { this.square = square; } @Override public double calculateArea() { // Calculate the area of a rectangle by using the square's side length as both the length and width double sideLength = square.getSideLength(); return sideLength * sideLength; } } // Existing Square class public class Square { private double sideLength; public Square(double sideLength) { this.sideLength = sideLength; } public double getSideLength() { return sideLength; } public double calculateArea() { return sideLength * sideLength; } } // Main application public class Main { public static void main(String[] args) { // Create a Square object Square square = new Square(5); // Assume a side length of 5 // Create a RectangleAdapter object, adapting the Square to work with rectangles RectangleAdapter rectangleAdapter = new RectangleAdapter(square); // Calculate the area of the square using the adapter double squareArea = square.calculateArea(); System.out.println("Area of the square: " + squareArea); // Calculate the area of a rectangle using the same adapter double rectangleArea = rectangleAdapter.calculateArea(); System.out.println("Area of the rectangle: " + rectangleArea); } }