Dart
Summary - Inheritance
Combine extends, super and override to write a shape hierarchy.
Summary - Inheritance
In this group you saw the building blocks of inheritance: extends, super, @override, abstract and implements. Now we will merge them in a shape hierarchy.
An abstract class Shape sets an abstract contract; Square and Circle concrete subclasses fill it. extends inherits, @override redefines methods, super calls the base constructor. Both subclasses share the same area contract but each writes its own area calculation. This is the foundation of polymorphism.
Exercise Write Shape and Square
Define abstract class Shape { double area(); }. Write a class named Square that inherits from Shape; add a final double side field and a Square(this.side) constructor. Write the @override double area() => side * side; method. In main, create an instance with var s = Square(3); and call print(s.area()).
Show example solution
// Define the Shape abstract class and the Square subclass
abstract class Shape {
double area();
}
class Square extends Shape {
final double side;
Square(this.side);
@override
double area() => side * side;
}
void main() {
var s = Square(3);
print(s.area());
}
Add the Circle subclass
In the second step we add another subclass to the hierarchy: Circle. It shares the same Shape contract but writes a different area calculation. This shows the power of polymorphism.
Example: class Circle extends Shape { final double radius; Circle(this.radius); @override double area() => 3.14 * radius * radius; }. In main both Square and Circle instances can be held by a Shape reference; each runs its own area version. The shared contract sits beside different behaviors.
Exercise Add the Circle subclass
Keep the existing Shape abstract class and Square subclass. Add a class named Circle that inherits from Shape; add a final double radius field, a Circle(this.radius) constructor and the @override double area() => 3.14 * radius * radius; method. In main, create an instance with var c = Circle(2); and call print(c.area()).
Show example solution
abstract class Shape {
double area();
}
class Square extends Shape {
final double side;
Square(this.side);
@override
double area() => side * side;
}
class Circle extends Shape {
final double radius;
Circle(this.radius);
@override
double area() => 3.14 * radius * radius;
}
void main() {
var c = Circle(2);
print(c.area());
}
Test yourself
-
Which is true for a Shape abstract class?
- Subclasses cannot use extends
- Shape() can be instantiated directly
- The area() body is written inside Shape
- Concrete subclasses must override the area() method
Show answer
Concrete subclasses must override the area() method — An abstract method must be overridden in the concrete subclass.
Next lesson: Module design