在Dart中實現面向對象編程通常需要定義類和對象。以下是在Dart中實現面向對象編程的基本步驟:
class Person {
String name;
int age;
Person(this.name, this.age);
void sayHello() {
print('Hello, my name is $name');
}
}
Person person = Person('Alice', 30);
print(person.name); // 輸出 Alice
person.sayHello(); // 輸出 Hello, my name is Alice
class Student extends Person {
String school;
Student(String name, int age, this.school) : super(name, age);
void study() {
print('$name is studying at $school');
}
}
class Animal {
void speak() {
print('Animal speaks');
}
}
class Dog extends Animal {
@override
void speak() {
print('Dog barks');
}
}
Animal animal = Dog();
animal.speak(); // 輸出 Dog barks
通過以上步驟,你可以利用Dart實現面向對象編程。