3. Dart OOP
3. Dart OOP
Object: An object is an instance of a class. Once a class is defined, you can create multiple objects based on that class.
class Person {
String name;
int age;
// Constructor
Person(this.name, this.age);
// Method
void introduce() {
print("Hello, my name is $name and I am $age years old.");
}
}
void main() {
// Creating an object of the Person class
Person person1 = Person('John', 25);
person1.introduce(); // Output: Hello, my name is John and I am 25 years old.
}
1-3 Encapsulation
Encapsulation is a fundamental
concept of Object-Oriented
Programming (OOP), including in Dart. It
refers to bundling the data (variables)
and methods (functions) that operate on
the data within a single unit, usually a
class, and restricting direct access to
some of the object’s components.
Encapsulation allows you to control
access to the data by exposing only
necessary parts through methods or
getters and setters, while keeping other
parts private.
1-4 Encapsulation Example
class BankAccount {
// Private field
double _balance = 0;
void main() {
BankAccount account = BankAccount();
account.deposit(1000);
print("Balance: ${account.getBalance()}");
// Output: Balance: 1000
}
1-5 Inheritance
Inheritance is a key concept in object-oriented programming (OOP),
where a class can inherit properties and methods from another class.
The class that inherits is called a subclass (or child class), and the class
being inherited from is the superclass (or parent class).
1-6 Inheritance Example
class Animal {
void makeSound() {
print('Animal makes a sound');
}
}
class Dog extends Animal {
@override
void makeSound() {
print('Dog barks');
}
}
void main() {
Dog dog = Dog();
dog.makeSound(); // Output: Dog barks
}
1-7 Inheritance Types
1-8 Polymorphism
Dart doesn’t have explicit interfaces like some other languages, but any class
can be treated as an interface. A class can implement multiple interfaces, and
this is a form of polymorphism where different classes can implement the same
interface in different ways.
1-9 Polymorphism Example
class Animal { void main() {
void makeSound() { Animal animal;
print('Animal makes a
sound'); animal = Dog();
} animal.makeSound(); // Output:
} Dog barks (Runtime
polymorphism)
class Dog extends Animal {
@override animal = Cat();
void makeSound() { animal.makeSound(); // Output:
print('Dog barks'); Cat meows (Runtime
} polymorphism)
} }