构造函数是一种不同类型的函数,它以与其类名相同的名称创建。构造函数用于在创建时初始化对象。当我们创建类对象时,那么构造函数会自动调用。它与类函数非常类似,但它没有明确的返回类型。生成构造函数是构造函数最常见的形式,用于创建类的新实例。
假设我们有一个类名 Student ,我们将创建一个如下目标。
Student std = new Student()
它调用 student 类的默认构造函数。
正如我们所提到的,构造函数与其类名具有相同的名称,并且它不会返回任何值。
class ClassName { ClassName() { } }
我们必须在创建构造函数时记住以下两种规则。
让我们了解以下示例。
void main() { //创建一个对象 Student std = new Student("Learnfk",26); } class Student{ //声明一个构造函数 Student(String str, int age){ print("The name is: ${str}"); print("The age is: ${age}"); } }
输出
The name is: Learnfk The age is: 26
在上面的示例中,我们创建了一个构造函数 Student(),它与类名相同。我们在构造函数中传递了两个传递的参数。
DART中有三种类型的构造函数,如下所述。
没有参数的构造函数称为默认构造函数或否arg构造函数。如果我们在类中声明,它会自动创建(没有参数)。如果我们创建具有参数或没有参数的构造函数,则DART编译器忽略默认构造函数。语法如下。
class ClassName { ClassName() { //构造函数体 } }
让我们了解以下示例。
void main() { //创建对象时自动调用构造函数 Student std = new Student(); } class Student{ //声明一个构造函数 Student(){ print("The example of the default constructor"); } }
输出
The example of the default constructor
我们还可以将参数传递给构造函数,该构造函数称为参数化构造函数。它用于初始化实例变量。有时,我们需要一个接受单个或多个参数的构造函数。参数化构造函数主要用于使用自己的值初始化实例变量。语法如下。
class ClassName { ClassName(parameter_list) //构造函数体 }
让我们了解以下示例。
void main() { //创建一个对象 Student std = new Student("Learnfk",26); } class Student{ //声明参数化的构造函数 Student(String str, int age){ print("The name is: ${str}"); print("The age is: ${age}"); } }
输出
The name is: Learnfk The age is: 26
命名构造函数用于在单类中声明多个构造函数。语法如下。
className.constructor_name(param_list)
让我们了解以下示例。
void main() { // 创建一个对象 Student std1 = new Student(); // Default构造函数的对象 Student std2 = new Student.namedConst("Computer Science"); // 参数化构造函数的对象 } class Student{ // 声明一个构造函数 Student(){ print("The example of the named constructor"); } // 第二个构造函数 Student.namedConst(String branch){ print("The branch is: ${branch}"); } }
输出
The example of the named constructor The branch is: Computer Science
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)
Tony Bai · Go语言第一课 -〔Tony Bai〕