Dart Classes

In this tutorial you will learn about the Dart Classes and its application with practical example.

Dart Classes

Dart is an object-oriented programming language; and supports the concepts of class, object, interfaces, inheritance, mixins, and abstract classes etc. In Dart, a class can be defined as a blueprint or prototype of associated objects. Class is a wrapper that binds/encapsulates the data and methods together; which can be later accessed by objects of that class. We can think of a class as user-defined data type, that describes the behavior and characteristics shared by all of its instances. Once a class has been defined, we can create instance or objects of that class which has access to class properties and methods.

Declaring a Class In Dart

In Dart, a class can be defined using the class keyword followed by the class name; and the class body enclosed by a pair of curly braces ({}).

Syntax:-

Here, ClassName is replaced with the actual class name then in between the curly brackets {} we provide class definition. A class definition includes associated fields, constructors, getters, setters and methods.

Note:- As per the naming convention rules for identifiers; the class name should capitalize the first letter of each word (including the first word), and use no separators.

Example:-

The example declares a class Employee. The class has a three fielda named empName, empAge and empSalary . The showEmpInfo() is a simple function that prints the value of the class fields.

Recommended:-  Dart Sets

Creating Class Objects In Dart

Once a class has been defined, we can create instance or objects of that class which has access to class fields and function. In Dart, an object of a class can be created using new keyword followed by the class name. Below is general syntax to declare an object of a class.

Syntax:-

Here, objectName and ClassName is replaced with actual object name and the class name respectively. The <constructor_arguments> should be passed values if the class constructor is parameterized.

Example:-

Let’s create an object of the class Employee we have created above –

Accessing Instance Variable and Functions

In Dart, once we have got an instance of a class created, we can access properties and method of that class using property/method name separated by a dot (.) operator after the instance name as following –

Syntax for Property:-

Syntax for Method:-

Example:-

Output:-

dart_accessing_class_variables_functions

In this tutorial we have learn about the Dart Classes and its application with practical example. I hope you will like this tutorial.