Interface là một cách để định nghĩa ra các quy ước của các lớp. Nó cho phép bạn xác định phương thức và thuộc tính cần phải được thực thi. Dart không dùng từ khoá Interface mà bất kỳ class nào cũng có thể trở thành interface.
Các khái niệm chính:
Lớp áp dụng Interface được gọi là một triển khai của Interface đó
Từ khoá implements dùng để triển khai một Interface với lớp thông thường
Từ khoá extends dùng để triển khai một Interface với lớp abstract
1. Tạo Interface cơ bản
Ví dụ 1: Dùng class trực tiếp để làm Interface thì lúc này method makeSound phải buộc có body
// Define an interface
class Animal {
void
makeSound() {} // Required to have function body because using class directly
}
// Implementing the interface
class Dog implements Animal {
@override
void makeSound() {
print("Woof!");
}
}
class Cat implements Animal {
@override
void makeSound() {
print("Meow!");
}
}
void main() {
Animal dog = Dog();
Animal cat = Cat();
dog.makeSound(); // Output: Woof!
cat.makeSound(); // Output: Meow!
}
2. Interface có nhiều bản triển khai
Ví dụ 2: Interface với nhiều lớp triển khai
Trong ví dụ này chúng ta dùng một interface nhưng có hai lớp triển khai đó là Car và Bike
class Vehicle {
void start() {}
void stop() {}
}
// Triển khai interface cho lớp Car
class Car implements Vehicle {
@override
void start() {
print("Car is Starting !");
}
@override
void stop() {
print("Car is stopping !");
}
}
// Triển khai interface cho lớp Bike
class Bike implements Vehicle {
@override
void start() {
print("Bike is starting !");
}
@override
void stop() {
print("Bike is stopping !");
}
}
// Gọi
void main() {
Vehicle car = Car();
Vehicle bike = Bike();
car.start(); // output : Car is Starting !
bike.start(); // output: Bike is starting !
}
3. Triển khai interface với abstract class
Ví dụ 3: dùng Abstract class như một interface, nhưng thay vì implements thì chúng ta dùng từ khoá extends và trước lớp dùng làm interface chúng ta thêm từ khoá abstract.
abstract class Shape {
double area(); // không cần có thân method
}
// Triển khai Circle (hình tròn) interface theo lớp shape
class Circle extends Shape {
double radius;
Circle(this.radius); // constructor nhận tham số
@override
double area() {
return 3.14 * radius * radius; // trả về chu vi của hình tròn
}
}
// Triển khai một tứ diện
class Rectangle extends Shape {
double width;
double height;
Rectangle(this.width, this.height);
@override
double area() {
return width * height;
}
}
void main() {
Shape circle = Circle(5);
Shape rectangle = Rectangle(2, 3);
print(circle.area()); // 78.5
print(rectangle.area()); // 6.0
}