static关键字用于声明类变量和方法。它通常为全局数据变量管理内存。静态变量和方法是类的成员,而不是单个实例。静态变量或方法对于类的每个实例都是相同的,因此,如果将数据成员声明为静态,则无需创建对象即可访问它。不需要类对象来访问静态方法或变量,我们可以通过将类名放在静态变量或方法之前来访问它。使用类名,我们可以从其他类中调用类方法。
Dart提供了static关键字来声明static变量。通过使用static关键字和变量名来声明它。语法在下面给出。
static [data_type] [variable_name];
我们可以通过使用类名本身而不是创建它的对象来访问静态变量。语法在下面给出。
链接:https://www.learnfk.comhttps://www.learnfk.com/dart-programming/dart-static-keyword.html
来源:LearnFk无涯教程网
ClassName.staticVariableName;
静态方法的概念也类似于静态变量。静态方法是类的成员,而不是类实例。静态方法只能使用静态变量,并且可以调用类的静态方法。我们不需要创建类的实例来对其进行访问。当我们想在其他类中使用静态方法时,该方法很有用。
我们可以通过使用返回类型使用static关键字后跟方法名称声明静态方法。
static return_type method_name() { //statement(s) }
可以使用类名来调用静态方法,而不是创建对象。
className.staticMethod();
让我们了解以下示例。
class Student { static String stdBranch; //声明静态变量 String stdName; int roll_num; showStdInfo() { print("Student's name is: ${empName}"); print("Student's salary is: ${roll_num}"); print("Student's branch name is: ${stdBranch}"); } } void main() { Student std1 = new Student(); //创建学生类实例 Student std2 = new Student(); //使用类名分配静态变量的值 Student.stdBranch = "Computer Science"; std1.stdName = "Ben Cutting"; std1.roll_num = 90013 std1.showStdInfo(); std2.stdName = "Peter Handscomb"; std2.roll_num = 90014 std2.showStdInfo(); }
输出
Student's name is: Ben Cutting Student's salary is: 90013 Student's branch name is: Computer Science Student's name is: Peter Handscomb Student's salary is: 90014 Student's branch name is: Computer Science
在上面的代码中,我们声明了一个名为Student的类,该类具有三个字段,包括静态变量stdBranch和一个方法showStdInfo()。我们创建了Student类的两个实例,并为类变量分配了值。
通过使用类名称和分配的值访问静态变量stdBranch。然后,我们通过对象std1和stu2调用showStdInfo()函数。它将学生的详细信息打印为输出。
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)