在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实现面向对象编程。