We made it! Part 5 of the object oriented programming series. we will be discussing what is the purpose, use cases, and what does encapsulation even mean. Encapsulation is use to hide a specific property or method only making those properties accessible within the scope of the function.
A real world example would be if you are with some friends. And you have a piece of cake in a public environment, those friends have also have access to your piece of cake but if you take your piece of cake to another area which is private or protected then the piece of cake is no longer accessible to your friends. This is a real world example of encapsulation.
File: cake.dart
library cake;
class MainCake{
//non-private property
//list of strings
List<String> randomPieceOfCakes = ['cake3', 'cake4', 'cake5', 'cake6'];
//private properties
String _pieceOfCake1 = "cake1";
String pieceOfCake2 = "cake2";
}
File: main.dart
import 'cake.dart';
void main(){
MainCake newCake = new MainCake();
//non-private property - randomPieceOfCakes
print(newCake.randomPieceOfCakes);
//private property - piece of cake
print(newCake._pieceOfCake1); // private property error
// non-private private - piece of cake
print(newCake.pieceOfCake2);
}
NOTE: Encapsulation in Dart happens at library level instead of class level unlike other object oriented programming languages.
In Dart, (_) underscores in Dart are private. This wraps up the series on object oriented programming. Hope you enjoyed it!
Top comments (0)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.