Dart OOP
Dart OOP
OOP stands for Object-Oriented Programming.
Procedural programming is about writing functions that work on data.
Object-oriented programming is about creating objects that contain both data and functions.
Dart is an object-oriented language.
Every value in Dart is an object, even numbers, strings, lists and functions.
This is why values have properties and methods that you can use with a dot .:
Example
void main() {
print(7.isEven);
print('dart'.toUpperCase());
print([3, 1, 2].length);
}
Try it Yourself »
Result:
false
DART
3
Why Use OOP?
Object-oriented programming has several advantages:
- It gives your programs a clear structure.
- It keeps the code DRY, which stands for "Don't Repeat Yourself".
- It makes the code easier to change, fix and test.
- It lets you create reusable parts with less code.
Classes and Objects
Classes and objects are the two main parts of OOP.
A class is a template, or a blueprint, for objects.
An object is one thing that is created from a class.
Look at the table below to see the difference:
| Class | Objects |
|---|---|
| Fruit | Apple, Banana, Mango |
| Car | Volvo, Ford, Toyota |
| Person | Liam, Emma, Noah |
A class describes what every object of that kind has.
For example, every car has a brand and a year, and every car can drive.
The data of an object is stored in fields, and the functions of an object are called methods.
When you create an object, it gets all the fields and methods of its class, but with its own values.
A First Example
Here is a small class called Car, with two fields and one method.
We use it to create two car objects:
Example
class Car {
String brand;
int year;
Car(this.brand, this.year);
void drive() {
print('The $brand from $year is driving');
}
}
void main() {
var car1 = Car('Volvo', 2020);
var car2 = Car('Ford', 1969);
car1.drive();
car2.drive();
}
Try it Yourself »
Result:
The Volvo from 2020 is driving
The Ford from 1969 is driving
Both objects come from the same class, but each object has its own brand and year.
You will learn how this code works, step by step, in the next chapters.