Instance vs Static Members
Part of the Object Oriented Programming section of Coddy's Dart journey — lesson 17 of 110.
In Dart classes, members (variables and methods) can belong to either individual objects or to the class itself. Understanding this distinction is fundamental to organizing your code effectively.
Instance members belong to each object you create. Every object gets its own copy of instance variables, and instance methods operate on that specific object's data:
class Dog {
String name; // Instance variable
Dog(this.name);
void bark() { // Instance method
print('$name says woof!');
}
}
Dog dog1 = Dog('Buddy');
Dog dog2 = Dog('Max');
dog1.bark(); // Buddy says woof!
dog2.bark(); // Max says woof!Each Dog object has its own name. Changing one dog's name doesn't affect the other.
Static members belong to the class itself, not to any particular object. They're shared across all instances and accessed using the class name:
class Dog {
String name;
static int totalDogs = 0; // Static variable
Dog(this.name) {
totalDogs++;
}
}
Dog dog1 = Dog('Buddy');
Dog dog2 = Dog('Max');
print(Dog.totalDogs); // 2The totalDogs variable is shared - there's only one copy regardless of how many Dog objects exist. You access it through the class name Dog.totalDogs, not through an instance.
Challenge
EasyLet's build a visitor counter system for a museum that tracks both individual exhibit visits and overall museum statistics.
You'll organize your code into two files:
exhibit.dart: Define anExhibitclass that represents a museum exhibit. Each exhibit should have:- An instance variable
name(String) for the exhibit's name - An instance variable
visitorCount(int) starting at0to track how many people visited this specific exhibit - A static variable
totalVisitors(int) starting at0to track total visits across all exhibits - A constructor that takes the exhibit name
- A
recordVisit()method that increments both the exhibit'svisitorCountand the class'stotalVisitors - A
displayStats()method that prints the exhibit's information
- An instance variable
main.dart: Import your exhibit class and create two exhibits:- A
'Dinosaur Bones'exhibit - An
'Ancient Egypt'exhibit
displayStats()on each exhibit in the order they were created, then print the total visitors across all exhibits.- A
The displayStats() method should print in this exact format:
[name]: [visitorCount] visitorsFor the total visitors line, print:
Total museum visitors: [totalVisitors]Access the static variable using the class name Exhibit.totalVisitors.
Expected output:
Dinosaur Bones: 3 visitors
Ancient Egypt: 2 visitors
Total museum visitors: 5Cheat sheet
Class members in Dart can be either instance members (belonging to individual objects) or static members (belonging to the class itself).
Instance members are unique to each object. Every object has its own copy of instance variables:
class Dog {
String name; // Instance variable
Dog(this.name);
void bark() { // Instance method
print('$name says woof!');
}
}Static members are shared across all instances and accessed using the class name with the static keyword:
class Dog {
String name;
static int totalDogs = 0; // Static variable
Dog(this.name) {
totalDogs++;
}
}
// Access static members through the class name
print(Dog.totalDogs); // 2Static variables maintain a single shared value regardless of how many objects are created.
Try it yourself
import 'exhibit.dart';
void main() {
// TODO: Create a 'Dinosaur Bones' exhibit
// TODO: Create an 'Ancient Egypt' exhibit
// TODO: Record 3 visits to the Dinosaur Bones exhibit
// TODO: Record 2 visits to the Ancient Egypt exhibit
// TODO: Call displayStats() on each exhibit in order
// TODO: Print total museum visitors using Exhibit.totalVisitors
// Format: Total museum visitors: [totalVisitors]
}
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