Methods
Part of the Object Oriented Programming section of Coddy's Dart journey — lesson 6 of 110.
Methods are functions that belong to a class. They define the behaviors or actions that objects can perform.
Here is an example of a class with methods:
class Calculator {
void greet() {
print('Hello! I am a calculator.');
}
int add(int a, int b) {
return a + b;
}
int multiply(int x, int y) {
int result = x * y;
print('$x x $y = $result');
return result;
}
}Method signatures in Dart always include a return type. Use void when the method returns nothing.
Create a calculator object:
Calculator myCalc = Calculator();Call a method that needs no parameters:
myCalc.greet();Call methods with parameters and capture the return value:
int sumResult = myCalc.add(5, 3);
print(sumResult);Call a method that both prints and returns a value:
int product = myCalc.multiply(4, 7);Output:
Hello! I am a calculator.
8
4 x 7 = 28Methods can:
- Have a return type like
int add(int a, int b) - Return values using
return - Print output directly using
print() - Be
voidwhen they do not return anything
Key Point: Call methods on objects using the dot operator: object.methodName(args).
Challenge
EasyCreate a BankAccount class in bank_account.dart with:
- A
double balanceinstance variable set to0 - A
depositmethod that takes adouble amountand adds it tobalance - A
withdrawmethod that takes adouble amountand subtracts it frombalance - A
getBalancemethod that returns the currentbalance
Then in driver.dart, create an account, deposit 100, withdraw 30, and print the balance in the format: 'Current balance: $[balance]'
Cheat sheet
Methods are functions that belong to a class and define behaviors that objects can perform.
Define methods with a return type. Use void when the method returns nothing:
class Calculator {
void greet() {
print('Hello! I am a calculator.');
}
int add(int a, int b) {
return a + b;
}
int multiply(int x, int y) {
int result = x * y;
print('$x x $y = $result');
return result;
}
}Call methods on objects using the dot operator:
Calculator myCalc = Calculator();
myCalc.greet(); // No parameters
int sumResult = myCalc.add(5, 3); // With parameters, capture return value
print(sumResult);
int product = myCalc.multiply(4, 7); // Prints and returnsMethods can have return types, return values using return, print output directly using print(), or be void when they don't return anything.
Try it yourself
import 'bank_account.dart';
void main() {
BankAccount myAccount = BankAccount();
myAccount.balance = 0;
// TODO: Deposit 100
// TODO: Withdraw 30
// TODO: Print balance in format: 'Current balance: $[balance]'
// Hint: use .toInt() on the balance for clean output
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
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