×

Dart Classes

Dart is an object – oriented programming language that supports all the object-oriented programming concepts such as classes, objects, inheritance, data abstraction and data encapsulation.

A class can be defined as a prototype or blueprint of the object. It is a collection of all the similar types of objects. Class exhibits two main object-oriented programming features : data abstraction and data encapsulation.

  1. Data Abstraction – It is the method by which only the essential details are displayed.
  2. Data Encapsulation – It is the method of wrapping up of data and its behavior as a single unit.

Classes are the best example of data encapsulation as it wraps up the data members and member functions as a single unit, i.e., class. The actual internal working of the function is hidden from the user and hence data abstraction is also exhibited.

These members of the class can be accessed using the object of the class. After defining the class, we can create objects or instance of that class.

Syntax of Dart classes:

class class_name

{

            < fields >

            < getters / setters >

            < constructors >

            < functions >

}

Here, class_name refers to the name of the class and the definition of the class lies between the curly braces ‘{ }’. It can contain following things in class :

  1. Fields – Fields refer to the variables declared in the class. They represent the data related to the objects.
  2. Getters and setters are used to initialize and retrieve the values of the fields of a class. By default, every class has a getter and setter however, we can override them explicitly.
  3. Constructors or destructors – Constructors are used to allocate the memory to the objects of a class, while the destructors are sued to deallocate the memory when the objects are no more in scope.
  4. Functions – Functions are the behavior of the object. Often referred to as methods, they contain the definition of actions to be performed on object.

Creating the object of the class

After defining the class, its object can be created to access the data members or member functions of that class. In Dart, an object of that class can be created using the ‘ new ’ keyword followed by the class_name.

Syntax of creating object :

var object_name = new class_name( < constructor_arguments > ) ;

Here, object_ name refers to the name that you assign to that object, class_name refers to the name of the class. Class_name ( < constructor_arguments > ) invokes the constructor.  Some values must be passed in the < constructor_arguments > part if the constructor is parameterized.

Example :

var s1 = new student( ) ;

var s2 = new student( 5 ) ;

Accessing Instance Variable and Functions of the class

To access the members of a class, dot operator (.) is used along with the object_name.

Syntax :

object.data_member ;

object.member_function( ) ;

Program

// definition of the class students

class Students

{

   // data members of the class

   var sName = ' Yukta ' ;

   var sAge = 19 ;

   var sCourse = ' BCA ' ;

  // member function of the class

  display( )

  {

    print( " Name of the students is : ${ sName } " ) ;

    print( " Age of the student is : ${ sAge } " ) ;

    print( " Course student is enrolled in : ${ sCourse } " ) ;

  }

  }

void main( )

{

  var s = new Students( ) ; // declaring the object of the class students

  print( ' \n Details of the student is : ' ) ;

  s.display( ) ; // accessing the display( ) function of the class using its object

}

Output :

Details of the student is :

Name of the students is : Yukta

Age of the student is : 19

Course student is enrolled in : BCA

Getters and Setters in Dart

Getter and setter methods are the methods that manipulate the data of the class fields. They are the methods that are used to read or write the properties of an object. Getter is used to read or get the data of the class field whereas setter is used to write or set the data of the class field to some variable.

Getter Method in Dart

It is used to retrieve a particular class field and save it in a variable. All classes have a default getter method but it can be overridden explicitly.

Consider the syntax of creating a getter in the class :

Syntax :

return_type get field_name {

    . . .

}

Setter Method in Dart

It is used to set the data inside a variable received from the getter method. All classes have a default setter method but it can be overridden explicitly.

Consider the syntax of creating a setter in the class :

Syntax :

set field_name {

    ...

}

Program

Consider the following code in Dart that explains the concept of Getter and Setter in Dart :

// defining a class named student

class student {

  // initializing sName property

  String sName = ' null ' ;




  /* creating a getter method getName

   * to input value of sName from the user */

  String get getName {

    // returning the value of sName

    return sName ;

  }




  /* creating a setter method setName

   * to set the value of sName */

  set setName( String name ) {

    sName = name ;

  }

}

void main( ) {

  // initializing the object s1 of the class student

  student s1 = student( ) ;




  // Calling the set_name method(setter method we created)

  // To set the value in Property " This is the tutorial for classes ! "

  s1.setName = " This is the tutorial for classes ! " ;




  // Calling the get_name method(getter method we created)

  // To get the value from Property " sName ”

  print( " Hey, ${ s1.getName } " ) ;

}

Output

Hey, This is the tutorial for classes !

Instance and Class Methods in Dart

We can create methods/functions in the Dart classes to perform specific actions. They help reduce the complexity of the code by avoiding writing the same lines of code repeatedly. As we already know, like the Dart functions, methods of classes may and may not return any value, and also, they may or may not take any parameter as input.

There are mainly two types of methods in Dart:

  1. Instance Method / Object Method
  2. Class Method

Instance Method in Dart :

These are the normal instance methods of the class that are used to access instance variables. By default, the member functions of the class are instance methods unless declared static. To use this method in the class, you must first create an object.

Syntax :

// Declaring an instance method

return_type method_name( )

{

  // Body of this method

}



// Creating an object of the class

class_name object_name = new class_name( ) ;



// Calling instance method

object_name.method_name( ) ;

Creating instance method in Dart :

// Creating a class 'add’

class add {

    // Initializing instance variables a and b

    int a = 0 ;

    int b = 0 ;

 

    /* Creating an instance method with two

     * arguments and a return type of integer */

    void sum( int c, int d )

    {

        /* Using this keyword to set the values

         * of the input to instance variable */

        this.a = c ;

        this.b = d ;

 

        // printing the sum of two numbers

        print( ' Sum of numbers is ${ a + b } ' ) ;

    }

}

 

void main( )

{

    // Creating an object ' a1 ' of the class ' add '

    add a1 = new add( ) ;

 

    // Calling the method sum with the use of object

    a1.sum( 5, 4 ) ;

}

Output :

Sum of numbers is 9

Class Method in Dart :

Other than instance methods, there is another type of member function known as the class method. These class methods can be created using the 'static' keyword. An important point to remember here is that static member functions of the class can only access state data members. They can't access or invoke non-static members of the class. 

The static member functions of the class can be invoked or called without using the object of the class.

Syntax :

// Creating class method

static return_type method_name( ) {

   // Body of method

}




// Calling class method

class_name.method_name( ) ;

Creating class method in Dart –

// Creating the class named ' add '

class add

{

    /* defining the static member function

     * 'sum' of this class with void as

     * return type and two integer arguments */

    static void sum( int c, int d )

    {

        // Printing the sum of these two numbers

        print( ' Sum of numbers is ${ c + d } ' ) ;

    }

}

 

void main( )

{

    /* invoking the ' sum ' function of the class

     * without using any object */

    add.sum( 5, 4 ) ;

}

Output :

Sum of numbers is 9

Constructors

Constructors are the special functions of classes that are used to initialize the objects when created in the program. Every class has one default constructor which is automatically called whenever an object is created. However, we can define the constructor explicitly also. They have the same name as the class name and do not have any return type.

Syntax :

class_name( < paremeters > )

{

            // body of the constructor

}

Here, the ‘class_name’ refers to the name of the class whose constructor has to be created. The ‘parameters’ refer to the arguments passed to the constructor. However, it is optional.

The body of the constructor contains sever lines of code that explains the functionality of the constructor.

Following are the types of constructors in Dart classes :

  1. Default Constructor
  2. Parameterized Constructor
  3. Named Constructor

Consider the following code in Dart that explains the concept of constructors

// Defining the class student

class student

{

   

  /* defining the constructor of the class student

   * with the same name as of the class, and no r

   * return type */

student( )

{

    /* Everytime the constructor is invoked, this

     * line is printed */

    print( ' Constructor is being invoked ! ' ) ;

  }

   

  // initialzing a string str

  String str = ' NULL ' ;

   

  // Creating Function inside class

  void display(){

    print( " The string is $str " ) ;

  }

}

void main( )

{

   

  // Creating an object s1 of the class student

  student s1 = new student();

   

  /* Accessing the instance variable str using

   * the object and intializing it with some

   * value */

  s1.str = ' This tutorial explains constructor also ! ' ;

   

  /* Accessing the instance function display using

   * the object to display the value of string */

  s1.display();

}

Output

Constructor is being invoked !

The string is  This tutorial explains constructor also !

As you can see, before any string the line inside the constructor is printed even though it is no where called. This is so because, the moment we create an object of the class, the compiler is automatically invoked. In this case, the first line in main( ) was the object creation, therefore this line got printed first.

Destructors

Destructors are the special functions in the class that are used to de-allocate the memory assigned to the objects as soon as they reach out of their scope. However, we don't need to actively delete objects in Dart. Dart is a garbage-collected language, so any object that we don't hold any references to will eventually be garbage collected and freed by the runtime system.

Advantages of Objects

There are various benefits of using object-oriented programming. Below are the few benefits :

  1. Modularity - The source code of an object can be maintained individually and can hide from the other object's source code.
  2. Data – hiding - Using oops programming, the details of the internal functionality of code are hidden from the others. For example - Users only interact with the application, but they don't familiar with the internal implementation.
  3. Reusability - We don't need to write the same code again and again. We can use the object of class multiple times in our program.
  4. Pluggability and debugging easy - If any object is creating a problem in our program, and then we can replace it in our program and plug the new object as its replacement. The oops code can be easy to debug.

Related Topics

Dart Symbols

Symbols data type in Dart A symbol is an object that is the representation of an operator or identifier in Dart. These are compile-time constants.  They are used in APIs that refer...

1 minute read.

Dart lists data type

The most important data type in any programming language is an ordered list of elements, an array. Dart lists resemble JavaScript array lists. Example,               var...

7 minutes read.

Dart Installation Guide

There are various ways of compiling and running an application created in Dart, either by compiling the Dart code to JavaScript using the Dart2js tool or by running on the...

3 minutes read.

Dart If statement

If statement is used to set the control on the lines of code. Using if statement, block of code is executed only if the expression in the statement returns true....

1 minute read.

Dart Miscellaneous types

Some Other Data types in Dart Apart from the data types studied so far, we have three other data types also which are as follows: NeverDynamicVoid Let us understand each one in detail, Never...

3 minutes read.

Rust vs Dart

Rust is a system-level programming language that stands next to C ++ in terms of syntax, but offers greater speed and memory security. Dart, on the other hand, is an...

2 minutes read.

Soundness in Dart

What is soundness? Soundness ensures that the program never comes across any invalid state that may lead to abrupt termination of the program. As its name suggests it ensures perfect type...

4 minutes read.

Dart Anonymous Function

Dart functions are the user defined functions that are designed to perform specific task. The use case of the functions is that they can be directly called any number of...

3 minutes read.

Dart Assignment Operator

Assignment operators are the operators that assign value to the variables. The value on the right-hand side is assigned to the variable on the left-hand side. We can also use...

4 minutes read.

Dart Objects

Apart from the built-in data types, Dart offers some other data types that have a special role to play. One of them is Objects.  Objects Objects are the foundation of the...

3 minutes read.

C++ vs Dart

Difference between C++ and Dart C++ is an object-oriented programming language developed in 1980 by Bjarne Stroustrup. It has wide real-world applications with various in-built functions and a very vast library...

1 minute read.

Dart Optional Parameters

Dart functions can have optional parameters with default values. When we create a function, we can specify parameters that calling code can provide; but if the calling code chooses not...

2 minutes read.

Golang vs Dart

Go is the procedural programming language. It was founded in 2007 by Robert Griesemer, Rob Pike, and Ken Thompson at Google but was launched in 2009 as the language of...

2 minutes read.

Lexical Scope and Closure

Lexical Scope : Lexical scope is a very important term in any programming language. It defines the scope of the variable based on the block it is contained inside. According to...

2 minutes read.

Dart Type Test Operators

Type Test Operators in Dart These operators are used to check the types of expressions at runtime. Dart is a typed language, and we often want to assert that a value...

1 minute read.

Dart Bitwise and Shift Operators

The Bitwise operators are the operators that perform different operations bit by bit on the value of the two operands. List of Bitwise Operators in Dart Sr. Operators Description 1. & ( Binary AND ) It returns...

2 minutes read.

Common Collection Methods

Most of the programming languages have arrays as a way to list items together. However, Dart has a collection of data structures similar to array. These are supported by the...

3 minutes read.

Dart Type inference

The task of interpreting the data types of fields, methods, local variables and most generic type arguments is handled by the static analyser. However, when not enough information is provided...

5 minutes read.

main function in Dart

The main( ) function is a predefined method in Dart that is also known as the entry-point of the program. The compiler begins the execution only when it comes across...

3 minutes read.

Assert in DART

In any programming language, resolving error is the most unwanted and tedious task. At times it becomes very difficult to find the error in the large code. Dart offers an...

3 minutes read.