Instance Variables
Part of the Object Oriented Programming section of Coddy's Dart journey — lesson 7 of 110.
Instance variables are variables declared inside a class. Each object created from the class gets its own copy of these variables, independent from all other objects.
Declare instance variables with a type and an optional default value:
class Student {
String school = 'Dart Academy'; // has a default value
String name = ''; // empty default
int age = 0; // zero default
}Variables with default values start with the same value for every new object. Variables like name and age start empty or zero until you set them.
Use a method with this to set individual object data:
class Student {
String school = 'Dart Academy';
String name = '';
int age = 0;
void setInfo(String name, int age) {
this.name = name; // this.name = instance variable
this.age = age; // this.age = instance variable
}
}Create students and assign their data:
Student student1 = Student();
Student student2 = Student();
student1.setInfo('Alice', 20);
student2.setInfo('Bob', 22);Access instance variables using the dot operator:
print('${student1.name} is ${student1.age} at ${student1.school}');
print('${student2.name} is ${student2.age} at ${student2.school}');Output:
Alice is 20 at Dart Academy
Bob is 22 at Dart AcademyNotice that school is the same for both objects because it has a default value, while name and age are unique to each object because they were set individually through setInfo.
Challenge
EasyComplete the Student class in student.dart:
- Declare a
String schoolinstance variable with default value'Dart Academy' - Declare a
String nameinstance variable with default value'' - Declare an
int ageinstance variable with default value0 - Add a
setInfomethod that takesString nameandint ageas parameters and sets them on the object usingthis
The driver.dart file will test your class by creating two students and printing their information (locked).
Cheat sheet
Instance variables are variables declared inside a class. Each object gets its own copy of these variables.
Declare instance variables with a type and an optional default value:
class Student {
String school = 'Dart Academy'; // has a default value
String name = ''; // empty default
int age = 0; // zero default
}Use a method with this to set individual object data:
class Student {
String school = 'Dart Academy';
String name = '';
int age = 0;
void setInfo(String name, int age) {
this.name = name; // this.name = instance variable
this.age = age; // this.age = instance variable
}
}Create objects and assign their data:
Student student1 = Student();
Student student2 = Student();
student1.setInfo('Alice', 20);
student2.setInfo('Bob', 22);Access instance variables using the dot operator:
print('${student1.name} is ${student1.age} at ${student1.school}');
// Output: Alice is 20 at Dart AcademyTry it yourself
import 'student.dart';
void main() {
Student student1 = Student();
Student student2 = Student();
student1.setInfo('Alice', 20);
student2.setInfo('Bob', 22);
print('${student1.name} is ${student1.age} at ${student1.school}');
print('${student2.name} is ${student2.age} at ${student2.school}');
}
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