Recap - Simple Calculator
Part of the Object Oriented Programming section of Coddy's Dart journey — lesson 9 of 110.
Challenge
MediumBuild a complete Calculator class in calculator.dart that brings together everything you have learned. The driver.dart file will import and test your class.
Your Calculator class must demonstrate all topics covered in this module:
- External Files:
calculator.dartwill be imported bydriver.dartusingimport 'calculator.dart'; - Libraries & Imports:
driver.dartusesimport 'dart:io'; - Introduction to OOP: Define
class Calculatorand create objects withCalculator() - Classes vs Objects: Each test creates a fresh
Calculatorobject with its own independent state - The this Keyword: Use
this.resultinside all methods to access the instance variable - Methods: Implement
add,subtract,multiply,divide,clear, andgetResult - Instance Variables: Declare
int result = 0as an instance variable - Constructor Basics: Add a
Calculator()constructor that setsresultto0and prints'Calculator ready'
Method requirements:
int add(int number)— addsnumbertoresult, returns new resultint subtract(int number)— subtractsnumberfromresult, returns new resultint multiply(int number)— multipliesresultbynumber, returns new resultint divide(int number)— dividesresultbynumberusing integer division (~/=), returns new result. Ifnumberis0, print exactly'Error: Division by zero'and return the unchanged resultvoid clear()— resetsresultto0int getResult()— returns the currentresult
Example usage:
Calculator calc = Calculator(); // prints: Calculator ready
calc.add(10); // result = 10
calc.multiply(3); // result = 30
calc.subtract(5); // result = 25
calc.divide(5); // result = 5
calc.divide(0); // prints: Error: Division by zero
calc.clear(); // result = 0Try it yourself
import 'calculator.dart';
import 'dart:io';
void main() {
String testCase = stdin.readLineSync()!;
if (testCase == 'constructor_test') {
Calculator calc = Calculator();
print('Initial result: ${calc.getResult()}');
print('Calculator created successfully');
} else if (testCase == 'addition_test') {
Calculator calc = Calculator();
int r1 = calc.add(10);
print('After adding 10: $r1');
int r2 = calc.add(5);
print('After adding 5: $r2');
print('Final result: ${calc.getResult()}');
} else if (testCase == 'subtraction_test') {
Calculator calc = Calculator();
calc.add(20);
int r1 = calc.subtract(8);
print('After subtracting 8 from 20: $r1');
int r2 = calc.subtract(2);
print('After subtracting 2: $r2');
print('Final result: ${calc.getResult()}');
} else if (testCase == 'multiplication_test') {
Calculator calc = Calculator();
calc.add(5);
int r1 = calc.multiply(4);
print('After multiplying by 4: $r1');
int r2 = calc.multiply(2);
print('After multiplying by 2: $r2');
print('Final result: ${calc.getResult()}');
} else if (testCase == 'division_test') {
Calculator calc = Calculator();
calc.add(100);
int r1 = calc.divide(4);
print('After dividing by 4: $r1');
int r2 = calc.divide(5);
print('After dividing by 5: $r2');
print('Final result: ${calc.getResult()}');
} else if (testCase == 'division_by_zero_test') {
Calculator calc = Calculator();
calc.add(50);
print('Initial value: ${calc.getResult()}');
int r = calc.divide(0);
print('Result after division by zero: $r');
print('Value unchanged: ${calc.getResult()}');
} else if (testCase == 'clear_test') {
Calculator calc = Calculator();
calc.add(25);
calc.multiply(3);
print('Before clear: ${calc.getResult()}');
calc.clear();
print('After clear: ${calc.getResult()}');
print('Current result: ${calc.getResult()}');
} else if (testCase == 'comprehensive_test') {
Calculator calc = Calculator();
calc.add(10);
calc.multiply(3);
calc.subtract(5);
calc.divide(5);
print('After sequence of operations: ${calc.getResult()}');
calc.divide(0);
print('After division by zero attempt: ${calc.getResult()}');
calc.clear();
calc.add(100);
print('After clear and add 100: ${calc.getResult()}');
} else {
print('Unknown test case');
}
}
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesLibraries & ImportsIntroduction to OOPClasses vs ObjectsThe this KeywordMethodsInstance VariablesConstructor BasicsRecap - Simple Calculator4Null Safety
Intro to Null SafetyNullable vs Non-NullableThe ? and ! OperatorsLate Keyword & Null SafetyNull-Aware OperatorsNull Safety in ClassesRecap - User Profile System7Abstract Classes & Interfaces
Abstract ClassesAbstract MethodsInterfaces in DartImplicit InterfacesImplementing vs ExtendingMultiple InterfacesRecap - Shape Calculator10Collections & Generics
List, Set, Map OverviewType-Safe CollectionsGeneric ClassesGeneric MethodsGeneric ConstraintsIterable & IteratorRecap - Generic Storage13Advanced OOP Concepts
Composition vs InheritanceExtension MethodsCallable ClassesSealed Classes (Dart 3)Records (Dart 3)Patterns & Matching (3.0)Enums with Methods16Project: Library Management
Project OverviewBook and User Classes2Constructors in Dart
Default ConstructorNamed ConstructorsInitializer ListsConstant ConstructorsFactory ConstructorsRedirecting ConstructorsRecap - Shape Builder5Encapsulation
Public vs Private MembersThe _ Prefix ConventionLibrary-Level PrivacyGetters & Setters DepthInformation HidingRecap - Student Records8Mixins
Introduction to MixinsCreating MixinsUsing Multiple Mixinson Keyword in MixinsMixin vs InheritanceMixin vs InterfaceRecap - Animal System11Special Methods
toString() OverridehashCode & == OverrideComparable Interfacecall() MethodnoSuchMethod OverrideRecap - Custom Collection14Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy Pattern3Class Properties
Instance vs Static MembersFinal & Const FieldsLate VariablesStatic Methods & FieldsGetters and SettersRecap - Bank Account Manager6Inheritance
Basic InheritanceThe super KeywordMethod OverridingThe @override AnnotationThe final Class KeywordConstructors & InheritanceRecap - Employee Hierarchy9Polymorphism
Polymorphism BasicsPolymorphism via InterfacesRuntime Type CheckingThe is & as OperatorsCovariant KeywordRecap - Payment Processor