Menu
Coddy logo textTech

Recap - Shape Calculator

Part of the Object Oriented Programming section of Coddy's Dart journey — lesson 49 of 110.

challenge icon

Challenge

Easy

Let's build a shape calculator system that brings together abstract classes and interfaces to create a flexible geometry toolkit. You'll design a class hierarchy where different shapes share common behavior through abstraction while each shape provides its own unique calculations.

You'll organize your code into three files:

  • shape.dart: Define your abstract base class and interface here:
    • An abstract class Shape with a String name property and constructor. Include abstract methods double calculateArea() and double calculatePerimeter(). Add a regular method describe() that prints [name] - Area: [calculateArea()], Perimeter: [calculatePerimeter()]
    • A Drawable class with a method draw() that prints Drawing shape...
  • shapes.dart: Import shape.dart and create your concrete shape classes:
    • A Rectangle class that extends Shape and implements Drawable. Add double width and double height properties. Calculate area as width * height and perimeter as 2 * (width + height). The draw() method should print Drawing rectangle [width]x[height]
    • A Circle class that extends Shape and implements Drawable. Add a double radius property. Use 3.14159 for pi. Calculate area as pi * radius * radius and perimeter (circumference) as 2 * pi * radius. The draw() method should print Drawing circle with radius [radius]
  • main.dart: Import shapes.dart and demonstrate your shape calculator:
    • Create a Rectangle named 'Rectangle' with width 5.0 and height 3.0
    • Create a Circle named 'Circle' with radius 4.0
    • For each shape, call draw() then describe()
    • Print an empty line between the two shapes

This challenge demonstrates how abstract classes define shared structure (every shape has area and perimeter calculations), while interfaces add additional capabilities (shapes that can be drawn). Each concrete class extends the abstract class for its core identity and implements the interface for extra functionality.

Expected output:

Drawing rectangle 5.0x3.0
Rectangle - Area: 15.0, Perimeter: 16.0

Drawing circle with radius 4.0
Circle - Area: 50.26544, Perimeter: 25.13272

Try it yourself

import 'shapes.dart';

void main() {
  // TODO: Create a Rectangle named 'Rectangle' with width 5.0 and height 3.0
  
  // TODO: Create a Circle named 'Circle' with radius 4.0
  
  // TODO: For the rectangle, call draw() then describe()
  
  // TODO: Print an empty line
  
  // TODO: For the circle, call draw() then describe()
}

All lessons in Object Oriented Programming