Skip to Content

Abstract Classes trong Dart

1. Giới thiệu

Abstract class không thể khởi tạo trực tiếp, dùng làm base class cho các class khác.

2. Khai báo Abstract Class

abstract class Shape { // Abstract method - không có body double area(); double perimeter(); // Concrete method - có implementation void describe() { print('This is a shape'); } }

3. Implement Abstract Class

abstract class Shape { double area(); double perimeter(); } class Circle extends Shape { double radius; Circle(this.radius); @override double area() => 3.14159 * radius * radius; @override double perimeter() => 2 * 3.14159 * radius; } class Rectangle extends Shape { double width, height; Rectangle(this.width, this.height); @override double area() => width * height; @override double perimeter() => 2 * (width + height); }

4. Abstract với concrete methods

abstract class Animal { String name; Animal(this.name); // Abstract method void makeSound(); // Concrete method void eat() { print('$name is eating'); } } class Dog extends Animal { Dog(String name) : super(name); @override void makeSound() { print('$name barks'); } }

5. Abstract properties

abstract class Drawable { // Abstract getter String get color; // Abstract setter set color(String value); void draw(); } class Circle extends Drawable { String _color = 'red'; @override String get color => _color; @override set color(String value) => _color = value; @override void draw() => print('Drawing $color circle'); }

6. Polymorphism với Abstract

void main() { List<Shape> shapes = [ Circle(5), Rectangle(4, 3), ]; for (var shape in shapes) { print('Area: ${shape.area()}'); } // var shape = Shape(); // Error! Không thể khởi tạo }

7. Factory trong Abstract Class

abstract class Database { void connect(); void query(String sql); factory Database(String type) { switch (type) { case 'mysql': return MySQLDatabase(); case 'postgres': return PostgresDatabase(); default: throw ArgumentError('Unknown database type'); } } } class MySQLDatabase implements Database { @override void connect() => print('Connecting to MySQL'); @override void query(String sql) => print('MySQL: $sql'); } class PostgresDatabase implements Database { @override void connect() => print('Connecting to PostgreSQL'); @override void query(String sql) => print('Postgres: $sql'); }

8. So sánh Abstract Class vs Interface

// Abstract class - có thể có implementation abstract class Animal { void eat() => print('Eating'); // Có body void speak(); // Abstract } // Interface (implicit) - chỉ định nghĩa contract class Flyable { void fly() {} } class Bird extends Animal implements Flyable { @override void speak() => print('Chirp'); @override void fly() => print('Flying'); }

📝 Tóm tắt

  • abstract class không thể khởi tạo trực tiếp
  • Abstract methods không có body
  • Subclass phải implement tất cả abstract methods
  • Có thể chứa cả abstract và concrete methods
  • Dùng cho định nghĩa interface và base class
Last updated on