OOP Concept in Dart
OOP Concept in Dart
Dart
HIMASHA GUNASENA
What is the OOP concept?
Object-Oriented programming is a way of programming that allow
“Objects” to represent data methods. There are key concepts:
1. Encapsulation
2. Inheritance
3. Polymorphism
4. Abstraction
Encapsulation
Encapsulation is the concept of wrapping data and method as a single
unit. Data/ method cannot be directly accessed to component. That
help to prevent the accidental modification of data.
Example:
class BankDetails {
int? _bankBalance;
void main(){
final bankDetails= BankDetails();
bankDetails.setNewBalance = 1000;
print(bankDetails.getBalance);
}
If need to access the data in private field, should use the getter and
setter
In, java has keyword private and public but dart hasn’t keywords. If we
need to create private variable or method in dart, we can use the
underscore (_),
Inheritance
Inheritance is concept that one class inherits the properties and
behaviors of another class. It provides code reusability. There is using
the extend keyword.
Type of Inheritance:
class Animal{
void eat(){
print(‘Eating’);
}
}
void main(){
Dog dog = Dog();
dog,eat();
dog.bark();
}
02. Multilevel Inheritance
A class is derived from another derived class.
class LivingBeing{
void breathe(){
print(‘breathing’);
}
}
void main(){
Dog dog = Dog();
dog,breathe();
dog,eat();
dog.bark();
}
03. Hierarchical Inheritance
Multiple classes inherit from shingle class
class Animal{
void eat(){
print(‘Eating’);
}
}
class Dog extends Animal {
void bark(){
print(‘barking’);
}
}
class Cat extends Animal {
void meow(){
print(‘meowing’);
}
}
void main(){
Dog dog = Dog();
Cat cat = Cat();
dog,eat();
dog,bark();
cat.eat();
cat.meow();
}
04. Multiple Inheritance
Dart doesn’t directly support Multiple heritance,
Mixins in dart are using for multiclass hierarchies. Mixin are normal
classes from which can borrow methods.
class Animal{
void eat(){
print(‘Eating’);
}
}
mixin CanFly{
void fly(){
print(‘flying’);
}
}
mixin CanSwim{
void swim(){
print(‘swiming’);
}
}
class Duck extends Animal with CanFly,CanSwim{
void quack(){
print(‘quacking’);
}
}
Polymorphism
Polymorphism allows methods to do different things based on the
object.
Example:
abstract class Animal {
void makeSound();
}
void main() {
Animal dog = Dog();
Animal cat = Cat();
dog.makeSound();
cat.makeSound();
}
Abstraction
Abstraction class refers to the process of hiding the complex
implementation details and showing only the essential features of an
object.
Example:
// Abstract Class: Shape
abstract class Shape {
void draw();
}
void main() {
Shape circle = Circle();
Shape rectangle = Rectangle();
circle.draw();
rectangle.draw();
}
Ready to dive into the world of app development?
Join me as we explore Flutter together
Thank You
Himasha Gunasena