This repository contains examples of Object-Oriented Programming (OOP) concepts in Dart, which is the programming language used in Flutter.
Each concept is explained with clear code samples and detailed explanations.
- Class and Object
- Constructor in Dart
- Access Modifiers
- Getter & Setter
- Static Members
- Inheritance
- Abstract Classes
// class_and_object.dart
class Car {
String brand = "Toyota";
String model = "Corolla";
void displayInfo() {
print("Car: $brand $model");
}
}
void main() {
Car myCar = Car(); // Create object
myCar.displayInfo();
}
- A class is a blueprint for creating objects.
- Car is the class, and myCar is an instance (object).
// constructor.dart
class Car {
String brand;
String model;
Car(this.brand, this.model); // Constructor
void displayInfo() {
print("Car: $brand $model");
}
}
void main() {
Car myCar = Car("Honda", "Civic");
myCar.displayInfo();
}- Constructors initialize objects when created.
- this.brand assigns values directly from parameters.
// access_modifiers.dart
class BankAccount {
String accountHolder;
double _balance; // Private variable
BankAccount(this.accountHolder, this._balance);
void deposit(double amount) {
_balance += amount;
print("Deposited: $amount");
}
void showBalance() {
print("Balance: $_balance");
}
}
void main() {
BankAccount account = BankAccount("John", 1000);
account.deposit(500);
account.showBalance();
}- Dart uses underscore _ to make members private within the same file.
- No keywords like private or public.
// getter_setter.dart
class Student {
String _name = "";
int _age = 0;
String get name => _name;
set name(String newName) {
if (newName.isNotEmpty) {
_name = newName;
}
}
int get age => _age;
set age(int newAge) {
if (newAge > 0) {
_age = newAge;
}
}
}
void main() {
Student student = Student();
student.name = "Kamal"; // Setter
student.age = 21; // Setter
print("Name: ${student.name}, Age: ${student.age}"); // Getter
}- Getter returns a value.
- Setter updates a value with validation logic.
// static.dart
class MathUtils {
static double pi = 3.14159;
static double square(double num) {
return num * num;
}
}
void main() {
print("Pi: ${MathUtils.pi}");
print("Square of 5: ${MathUtils.square(5)}");
}- static means the member belongs to the class, not an instance.
- Accessed using ClassName.memberName.
// inheritance.dart
class Animal {
void sound() {
print("Animal makes a sound");
}
}
class Dog extends Animal {
@override
void sound() {
print("Dog barks");
}
}
void main() {
Dog dog = Dog();
dog.sound();
}- extends means inheriting properties and methods from another class.
- @override changes parent method behavior.
// abstract_class.dart
abstract class Shape {
void draw(); // Abstract method
}
class Circle extends Shape {
@override
void draw() {
print("Drawing a Circle");
}
}
void main() {
Circle circle = Circle();
circle.draw();
}- Abstract classes cannot be instantiated.
- They act as a blueprint for subclasses.