Object-Oriented Programming for SmartyPants-DART EDITION. Part III~ Encapsulation ~
Welcome!! to Part 3 of this series.
The first two Pillars of OOP that we discussed were Inheritance and Abstraction. In this part, we will be discussing the meaning and usefulness of the third which is Encapsulation.
Encapsulation is used to hide a certain property or method, making it accessible only within the scope of a particular function. In order to do this, we make whichever identifier we're trying to hide private. The syntax for this is in Dart is to add an underscore _ in front of it's name.
Syntax:
_identifier
In Dart, any identifier that begins with an underscore is private to its library, this is different from languages like Java where a private identifier is only accessible by its class.
Private fields
A private field or property is only accessible within its library. Its value cannot be changed or even accessed directly from outside. This is useful when we don't want a value to be changed by accident perhaps by another programmer who is maintaining our code.
class Game{
String name;
int _score;
}
In the example above, we have defined score as a private field.
Private Methods
class Game{
void _log(){
print('Welcome to your new game!');
}
}
Here we have defined log as a private method. Say we try to do something like this..
File: game.dart
class Game{
void _log(){
print('Welcome to your new game!');
}
File: main.dart
void main(){
Game tetris=Game();
tetris._log(); //results into private property error.
}
}
We will end up with an error because log cannot be accessed like this outside of game.dart .
Accessing Private Methods and Properties.
So how can we ever make use of private properties and methods if we can't access them directly?. Well, we can declare and make use of special methods called getters and setters.
Getters are methods that simply return a value, they take no arguments. If we want to access a private property we can return the property inside a getter and call the getter method from outside the current file.
Meanwhile, setters can allow us to change a property from outside the current file.
File: game.dart
class Game{
String _username;
int _score=10;
void _log(){
print('Welcome to your new game!');
//getter
int get userScore {
return _score;
}
//setter
void set userName(String name){
_username=name;
}
}
File: main.dart
Game tetris = Game();
tetris.userName="Tommy"; //sets _username to Tommy
print(tetris.userScore) ; //outputs 10.
And that's it on Encapsulation in Dart. I hope this introduction to private properties and methods was well understood. Please feel free to leave questions and suggestions in the comments.
The next and final pillar of OOP we'll be addressing is Polymorphism so stay tuned for that.
Thanks for Reading! ๐