KatInterview

Build a Geometry Library with Interfaces and Classes

BehavioralModel answer
MediumModel answerBehavioralobject-oriented-designinterfacesencapsulation

Last updated

Create an abstract interface for geometric shapes and implement concrete classes for circles and rectangles with validation and immutability.

Problem

You're building a geometry library that needs to support various 2D shapes. Your task is to create a well-structured object-oriented design using an abstract interface and concrete implementations.

Build a Shape interface (or abstract base class) that defines the contract all shapes must follow, then implement two concrete shapes: Circle and Rectangle.

Interface Requirements

Your Shape interface must declare three methods:

  • area() — returns the shape's area as a float
  • perimeter() — returns the perimeter (circumference for circles) as a float
  • getInfo() — returns a descriptive string about the shape

Circle Implementation

Create a Circle class that:

  • Accepts a radius parameter in the constructor
  • Validates that radius is non-negative (raise an exception for invalid input)
  • Implements all three Shape methods correctly
  • Uses π ≈ 3.14159... for calculations

Rectangle Implementation

Create a Rectangle class that:

  • Accepts width and height parameters in the constructor
  • Validates that both dimensions are non-negative (raise exceptions for invalid input)
  • Implements all three Shape methods correctly

Design Constraints

  • Use proper encapsulation: dimension values should be stored in private/protected attributes
  • Objects must be immutable after construction — no changing dimensions later
  • All validation must happen in the constructor before any state is stored

Example Interaction

shapes = [Circle(5.0), Rectangle(4.0, 6.0)]

for shape in shapes:
    print(f"{shape.getInfo()}: Area={shape.area():.2f}, Perimeter={shape.perimeter():.2f}")

# Expected output:
# Circle (radius: 5.00): Area=78.54, Perimeter=31.42
# Rectangle (width: 4.00, height: 6.00): Area=24.00, Perimeter=20.00

You should be prepared to discuss your design choices and how they demonstrate OOP principles.

Hints

Hint 1

The interface should prevent instantiation of incomplete implementations — use abstract methods

Hint 2

Immutability means both preventing external modification and blocking new attributes from being added after construction

Hint 3

Validate all inputs before storing any state so invalid objects never exist