User Story
As a developer tasked with building a geometric application, I aim to establish a versatile framework for handling various geometric shapes. To achieve this, I will define a common interface named "Shape" with two essential methods: calculateArea() and calculatePerimeter(). These methods will allow any shape that implements the "Shape" interface to provide its own logic for calculating its area and perimeter.
Solution
Shape Interface Class:
public interface Shape {
Double calculateArea();
Double calculatePerimeter();
}
Circle Class:
public class Circle implements Shape {
private Double radius;
public Circle(Double radius) {
this.radius = radius;
}
public Double calculateArea() {
return Math.PI * Math.pow(radius, 2);
}
public Double calculatePerimeter() {
return 2 * Math.PI * radius;
}
}
Rectangle Class:
public class Rectangle implements Shape {
private Double length;
private Double width;
public Rectangle(Double length, Double width) {
this.length = length;
this.width = width;
}
public Double calculateArea() {
return length * width;
}
public Double calculatePerimeter() {
return 2 * (length + width);
}
}
Apex Code:
Shape circle = new Circle(5.0);
System.debug('Circle Area: ' + circle.calculateArea());
System.debug('Circle Perimeter: ' + circle.calculatePerimeter());
Shape rectangle = new Rectangle(4.0, 6.0);
System.debug('Rectangle Area: ' + rectangle.calculateArea());
System.debug('Rectangle Perimeter: ' + rectangle.calculatePerimeter());
Video
Video does not exists.