Understanding the Concepts of Classes and Objects in Dart

Understanding the Concepts of Classes and Objects in Dart

Dart is an object-oriented language, and every value we manipulate in a Dart program is an object. An object represents an instance of a class, and a class is a template or description of an object. We can also draw the following analogy. We all have some idea of a person – having two arms, two legs, a head and a torso. There is some pattern – this pattern can be called a class. A real person (actually an instance of this class) is an object of this class.

The class is defined using the class keyword:

class Person{                                          
}

The Person class is defined here. After the name of the class are curly brackets, between which the body of the class is placed – that is, its fields and methods.

Any object can have two main characteristics: state – some data that the object stores, and behavior – actions that the object can perform.

To store the state of an object in a class, use the fields or variables of the class. Methods are used to determine the behavior of an object in a class. For example, a Person class that represents a person might have the following definition:

class Person{
     String name = "undefined";      // name
     int age = 0;                    // age
     void display(){
        print("Name: $name Age: $age");
    }
}

The Person class has two fields defined: name represents the person’s name, and age represents the person’s age. And the display method is also defined, which returns nothing and just outputs this data to the console.

It is worth considering that since the variables name and age represent the String and int types, which do not allow null values, we need to provide these variables with initial values. Or we could use nullable types, then providing initial values would be optional.:

class Person{
String? name;       // name
 int? age;           // age
  void display(){
  print("Name: $name Age: $age");
    }
}

Now we use this class. To do this, define the following program

void main (){
  Person tom;
}
class Person{ 
  String name = "undefined";      // name
  int age = 0;            // age
  void display(){
       print("Name: $name Age: $age");
    }
}

A class represents a new type, so we can define variables that represent a given type. So, here in the main function, the tom variable is defined, which represents the Person class. But so far, this variable does not point to any object and by default it has the value null. By and large, we can’t use it yet, so first you need to create an object of the Person class.

Constructors

In addition to the usual methods, classes can define special methods, which are called constructors. Constructors are called when creating a new object of this class. Constructors perform object initialization.

If no constructor is defined in a class, a constructor without parameters is automatically created for that class.

The above defined Person class has no constructors. Therefore, a default constructor is automatically created for it, which we can use to create a Person object. In particular, we will create one object:

void main (){
    Person tom = Person();
    tom.display();
    // change name and age
    tom.name = "Tom";
    tom.age = 35;
    tom.display();
}
class Person{
    String name = "undefined";
    int age = 0;
    void display(){
        print("Name: $name Age: $age");
    }
}

To create a Person object, use the expression Person(). Older versions of Dart also used the new: Person tom = new Person (); operator to call the constructor. But in recent versions of Dart, the new operator can be omitted.

The default constructor does not accept any parameters. As a result, after executing this expression, a section will be allocated in memory where all the data of the Person object will be stored. And the tom variable will get a reference to the created object.

If the constructor does not initialize the values of the object variables, then they get the default values, that is, the null value (that is, the actual absence of a value).

After creating the object, we can access the variables and methods of the Person object via the tom variable. To do this, use the dot (.) operator – that is, we specify the name of the field or method through the dot: tom.name. For example, you can set or get the values of the fields: tom.name = “Tom”.

As a result, we will see on the console:

Name: indefinite Age: 0
Name: Tom Age: 35

Null and Classes

Like all other built-in types, classes by default represent a type that does not allow a null value. If we need an object of the class to store a null value, we can use the nullable class, that is, add the operator to the type definition ?:

void main (){
    Person? sam;
    print(sam);  // null    - sam accepts the value null
    Person tom;
    // print(tom);  // ! Error, tom can't accept null
}

In the case of the print(tom) call, as in the case of other types of variables that cannot take the null value, you must assign the variable an initial value before using it.

At the same time, when using nullable classes, we can get into the following situation. As mentioned above, to access the fields and methods of the object, the dot (.) operator is used, after which the name of the field/method is specified. However, as we know, if variables are not assigned a value, then they default to null, which may need to be taken into account. For example, we refer to the fields of an object through a variable that is not initialized:

void main (){
  Person? sam;
  sam.age = 23;// Error, sam = null
}
class Person{
 String name = "undefined";
 int age = 0;
 void display(){
    print("Name: $name Age: $age");
}

When executing a line of code sam. age = 23, the program throws an exception and completes its execution. Because we didn’t create an object of the Person class using the constructor. Therefore, the variable sam has the value null, that is, in fact, nothing, there is no object. Accordingly, we cannot access the fields of a non-existent object. To avoid this problem, we can use a different operator -?. to access the fields:

void main (){  
    Person sam;
    sam?.age =  19;
    sam?.display();
}
class Person{
    String name = "undefined";
    int age = 0;
    void display(){
        print("Name: $name Age: $age");
    }
}

The operator ?. check the value of the variable, if the variable is not null, then access to its fields and methods occurs. If it is null, the reference to the variable is ignored.

Recommended Articles

Share
Tweet
Pin
Share
Share