面向对象编程将对象定义为“具有已定义边界的任何实体”。对象具有以下内容 -
- 状态 - 描述对象,类的字段表示对象的状态。
- 行为 - 描述对象可以执行的操作。
- 标识 - 将对象与一组类似的其他对象区分开的唯一值。两个或多个对象可以共享状态和行为,但不能共享身份。
句点运算符(.)与对象一起使用以访问类的数据成员。
示例
Dart以对象的形式表示数据,Dart中的每个类都扩展了Object类。下面给出了一个创建和使用对象的简单示例。
class Student { 
   void test_method() { 
      print("This is a  test method"); 
   } 
   void test_method1() { 
      print("This is a  test method1"); 
   } 
}  
void main()    { 
   Student s1 = new Student(); 
   s1.test_method(); 
   s1.test_method1(); 
}
执行上面示例代码,得到以下结果 -
This is a test method 
This is a test method1
级联运算符(..)
上面的示例调用了类中的方法。但是,每次调用函数时都需要引用该对象。在存在一系列调用的情况下,级联运算符可用作速记。
级联(..)运算符可用于通过对象发出一系列调用。上述示例代码可以按以下方式重写。
class Student { 
   void test_method() { 
      print("This is a  test method"); 
   } 
   void test_method1() { 
      print("This is a  test method1"); 
   } 
}  
void main() { 
   new Student() 
   ..test_method() 
   ..test_method1(); 
}
执行上面示例代码,得到以下结果 -
This is a test method 
This is a test method1
toString()方法
此函数返回对象的字符串表示形式。请查看以下示例以了解如何使用toString方法。
void main() { 
   int n = 212; 
   print(n.toString()); 
}
执行上面示例代码,得到以下结果 -
212
