面向對象編程將對象定義為“具有已定義邊界的任何實體”。對象具有以下內容 -
- 狀態 - 描述對象,類的字段表示對象的狀態。
- 行為 - 描述對象可以執行的操作。
- 標識 - 將對象與一組類似的其他對象區分開的唯一值。兩個或多個對象可以共用狀態和行為,但不能共用身份。
句點運算符(.)與對象一起使用以訪問類的數據成員。
示例
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
