Menu
Coddy logo textTech

Recap - Shape Builder

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

challenge icon

Challenge

Easy

Let's build a Rectangle class that brings together all the constructor techniques you've learned in this chapter. You'll create a versatile shape class that can be instantiated in multiple ways.

You'll organize your code into two files:

  • rectangle.dart: Define a Rectangle class with the following:
    • Two final double fields: width and height
    • Two computed final double fields: area and perimeter
    • A main constructor that takes width and height, using an initializer list to calculate area (width × height) and perimeter (2 × (width + height))
    • A named constructor Rectangle.square(double side) that redirects to the main constructor with equal width and height
    • A named constructor Rectangle.golden(double width) that creates a rectangle using the golden ratio (height = width × 1.618), redirecting to the main constructor
    • A constant constructor Rectangle.unit() that creates a 1×1 rectangle (you'll need a separate const constructor for this)
    • A display() method that prints the rectangle's information
  • main.dart: Import your rectangle class and create four rectangles:
    • A custom rectangle with width 4.0 and height 3.0
    • A square with side 5.0
    • A golden rectangle with width 10.0
    • A unit rectangle using the constant constructor (create it as a compile-time constant)
    Call display() on each rectangle in the order listed above.

The display() method should print in this exact format:

Rectangle [width]x[height] | Area: [area] | Perimeter: [perimeter]

Expected output:

Rectangle 4.0x3.0 | Area: 12.0 | Perimeter: 14.0
Rectangle 5.0x5.0 | Area: 25.0 | Perimeter: 20.0
Rectangle 10.0x16.18 | Area: 161.8 | Perimeter: 52.36
Rectangle 1.0x1.0 | Area: 1.0 | Perimeter: 4.0

Try it yourself

import 'rectangle.dart';

void main() {
  // TODO: Create a custom rectangle with width 4.0 and height 3.0

  // TODO: Create a square with side 5.0

  // TODO: Create a golden rectangle with width 10.0

  // TODO: Create a unit rectangle using the constant constructor
  // (create it as a compile-time constant using 'const')

  // TODO: Call display() on each rectangle in the order listed above
}

All lessons in Object Oriented Programming