In this tutorial you will learn about the Dart Object and its application with practical example.
Dart Object
Dart is an object oriented programming language. Everything in Dart is associated with classes and objects, along with its attributes and methods. A Class is like a blueprint for creating objects. An object is an variable (or instance) of a class; objects have the behaviors of their class. An object has a state and behavior associated with it. The state of an object is stored in fields (variables), while methods (functions) represents the object’s behavior. An object is created from a template known as class.
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:-
1 |
var objectName = new ClassName(<constructor_arguments>); |
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:-
Employee Class
1 2 3 4 5 6 7 8 9 10 11 |
class Employee { var empName; var empAge; var empSalary; showEmpInfo(){ print("Employee Name Is : ${empName}"); print("Employee Age Is : ${empAge}"); print("Employee Salary Is : ${empSalary}"); } } |
Let’s create an object of the class Employee we have created –
1 |
var emp = new Employee(); |
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:-
1 |
objectName.propName |
Syntax for Method:-
1 |
objectName.methodName() |
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
class Employee { var empName; var empAge; var empSalary; showEmpInfo(){ print("Employee Name Is : ${empName}"); print("Employee Age Is : ${empAge}"); print("Employee Salary Is : ${empSalary}"); } } void main(){ var emp = new Employee(); emp.empName = "John"; emp.empAge = 30; emp.empSalary = 45000; print("W3Adda - Dart Access Class Property and Method"); emp.showEmpInfo(); } |
Output:-