Abstract Base Behavior
Lesson 35 of 48 in Coddy's Dart for C Developers course.
C has no abstract classes. Shared behavior is a function that takes the base struct and calls through a function pointer each concrete type supplies, so the shared code dispatches to the specialized part of the actual object. Nothing in C stops you from creating a base struct with a null function pointer, and calling it is undefined behavior. A Dart abstract class combines concrete shared methods with abstract requirements, and the compiler refuses to instantiate it directly.
An abstract class cannot be instantiated directly. It can combine abstract requirements with concrete shared behavior. Concrete methods may call specialized overrides supplied by subclasses.
Complete C program:
#include <stdio.h>
struct shape {
const char *(*name)(void); /* the part each concrete shape must supply */
};
static void shape_label(const struct shape *s) { printf("shape:%s\n", s->name()); }
static const char *circle_name(void) { return "circle"; }
int main(void) {
const struct shape circle = {circle_name};
shape_label(&circle);
return 0;
}
Complete Dart program:
abstract class Shape{String name();String label()=>'shape:'+name();}
class Circle extends Shape{String name()=>'circle';}
void main(){print(Circle().label());}Challenge
EasyImplement abstract Charge with abstract cost(int units) and concrete pair(int a,int b) summing the two costs using dynamic dispatch. FlatCharge(int fee) extends Charge: cost is zero for zero units, fee otherwise. UnitCharge(int rate) extends Charge: cost is rate times units. Input is mode flat or unit, amount, a and b, all integers nonnegative at most 100. Output pair.
Do not print from editable files. The supplied exercise.dart parses input and returns output; the locked driver independently probes the public APIs and prints the result with one newline.
Your code goes in Charge.dart, FlatCharge.dart, UnitCharge.dart, exercise.dart. main.dart holds the supplied input/output code and cannot be edited.
Try it yourself
import 'dart:io';
import 'dart:convert';
import 'exercise.dart';
import 'Charge.dart';
import 'FlatCharge.dart';
import 'UnitCharge.dart';
void check(bool condition){if(!condition)throw StateError('Public API contract failed');}
Future<void> main() async {
final raw=await stdin.transform(utf8.decoder).join();
final input=raw.replaceFirst(RegExp(r'\r?\n$'),'');
final Charge a=FlatCharge(7),b=UnitCharge(3);check(a.cost(0)==0 && a.cost(2)==7 && a.pair(1,2)==14);check(b.cost(4)==12 && b.pair(2,3)==15);
stdout.writeln(solve(input));
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Dart for C Developers
1First Dart Programs
Run Dart FilesOutput and CommentsImports and LibrariesBindings and TypesNumeric OperationsRecap: Parcel Invoice4Collection Pipelines
Iterables and LazinessMaps and Missing KeysSets and MembershipClosures and CallbacksSorting and ComparatorsRecap: Word Inventory7Contracts and Reuse
Inheritance and OverridesImplicit InterfacesAbstract Base BehaviorGeneric ClassesMixins and ReuseEnums and StateRecap: Transform Pipeline3Functions and Values
Functions and ReturnsNamed ParametersNull SafetyStrings and UnicodeLists and MutationRecap: Record Readings6Objects and State
Classes and InstancesConstructors and FactoriesProperties and PrivacyIdentity and CopiesComposition Across FilesRecap: Bounded Counter9Parcel Depot Project
Depot: Valid ItemsDepot: Register StockPractice on your own: Online Dart compiler