Category: 5. Object-Oriented

https://cdn3d.iconscout.com/3d/premium/thumb/spiral-object-10293243-8431858.png?f=webp

  • What is constructor?

    A constructor is a different type of function which is created with same name as its class name. The constructor is used to initialize an object when it is created. When we create the object of class, then constructor is automatically called. It is quite similar to class function but it has no explicit return type. The generative constructor is the most general form of the constructor, which is used to create a new instance of a class.

    It is option to declare within the class. All class have own constructor but if we don’t declare or forget then Dart compiler will create default constructor automatically by passing the default value to the member variable. If we declare own constructor, then default constructor will be ignored.

    Example –

    Suppose we have a class name Student and we will create an object of it as follow.

    Student std = new Student()  

    It invoked the default constructor of the Student class.

    Creating Constructor in Dart

    As we have mentioned, a constructor has the same name as its class name and it doesn’t return any value. Suppose if we have class Student then the constructor name should be also Student.

    Syntax:

    class ClassName {  
    
         ClassName() {  
    
    }  
    
    }  

    We must remember the following two rules while creating a constructor.

    • The constructor name should be same as the class name.
    • The constructor doesn’t have explicit return type.

    Let’s understand the following example.

    Example –

    void main() {  
    
          // Creating an object   
    
          Student std = new Student("Jones",26);  
    
    }  
    
    class Student{  
    
         // Declaring a construstor   
    
         Student(String str, int age){  
    
              print("The name is: ${str}");  
    
              print("The age is: ${age}");  
    
      
    
                 }  
    
    }

    Output

    The name is: Jones
    The age is: 26
    

    Explanation:

    In the above example, we created a constructor function Student() which is same as the class name. We passed two passed parameter in the constructor and when we instantiated an object of Student class and passed value it automatically called the constructor then printed the result.

    Types of Constructors

    There are three types of constructors in Dart as given below.

    • Default Constructor or no-arg Constructor
    • Parameter Constructor
    • Named Constructor

    Default Constructor or no-arg Constructor

    A Constructor which has no parameter is called default constructor or no-arg constructor. It is automatically created (with no argument) by Dart compiler if we don’t declare in the class. The Dart compiler ignores the default constructor if we create a constructor with argument or no argument. The syntax is given below.

    Syntax:

    class ClassName {  
    
       ClassName() {  
    
       // constructor body  
    
       }  
    
    }

    Let’s understand the following example.

    Example –

    void main() {  
    
          // Call constructor automatically when we creates an object   
    
          Student std = new Student();  
    
    }  
    
      
    
    class Student{  
    
         // Declaring a construstor   
    
         Student(){  
    
              print("The example of the default constructor");  
    
                 }  
    
    } 

    Output

    The example of the default constructor
    

    Parameterized Constructor

    We can also pass the parameters to a constructor that type of constructor is called parameterized constructor. It is used to initialize instance variables. Sometimes, we need a constructor which accepts single or multiple parameters. The parameterized constructors are mainly used to initialize instance variable with own values. The syntax is given below.

    Syntax:

    class ClassName {  
    
       ClassName(parameter_list)  
    
      // constructor body  
    
    }  

    Let’s understand the following example.

    Example –

    void main() {  
    
          // Creating an object   
    
          Student std = new Student("Jones",26);  
    
    }  
    
    class Student{  
    
         // Declaring a parameterized constructor   
    
         Student(String str, int age){  
    
              print("The name is: ${str}");  
    
              print("The age is: ${age}");  
    
      
    
                 }  
    
    }

    Output

    The name is: Jones
    The age is: 26
    

    Explanation –

    In the above example, we declared a parameterized constructor which has two parameter name and age. We created an object of the Student class and passed the appropriate value to the constructor. It printed the name and age as an output to the screen.

    Named Constructors

    The named constructors are used to declare the multiple constructors in single class. The syntax is given below.

    Syntax:

    className.constructor_name(param_list)  

    Let’s understand the following example.

    Example –

    void main() {  
    
          // Creating an object   
    
          Student std1 = new Student();  // object for Default constructor  
    
          Student std2 = new Student.namedConst("Computer Science");  // object for parameterized constructor  
    
    }  
    
      
    
    class Student{  
    
         // Declaring a construstor   
    
         Student(){  
    
              print("The example of the named constructor");  
    
                 }  
    
          // Second constructor  
    
         Student.namedConst(String branch){  
    
              print("The branch is: ${branch}");  
    
      
    
               }  
    
    } 

    Output

    The example of the named constructor
    The branch is: Computer Science
    
  • Classes and Object

    Dart classes are the blueprint of the object, or it can be called object constructors. A class can contain fields, functions, constructors, etc. It is a wrapper that binds/encapsulates the data and functions together; that can be accessed by creating an object. A class can refer to as user-define data type which defines characteristics by its all objects.

    We can assume a class as a sketch (prototype) or a car. It contains all the details about model name, year, features, price, etc. Based on these properties of the car, we can build the car. Here the car is an object. There can be many cars so we can create many objects of cars to access all the properties.

    Defining a Class in Dart

    Dart provides class keyword followed by a class name is used to define a class; all fields and functions are enclosed by the pair of curly braces ({}). The syntax is given below.

    Syntax:

    class ClassName {  
    
       <fields>  
    
       <getters/setters>  
    
      <constructor>  
    
     <functions>  
    
    }

    Here, the ClassName represents the actual name of the class, which is defined by the user. In curly braces, we provide a class definition. A class can consist of fields, constructors, getters setters, and methods.

    Note – According to the naming convention rule of identifiers, the first letter of the class name must be capital and use no separators.

    Let’s understand the following example.

    Example –

    void main() {   
    
       // Defining class  
    
     class Student {  
    
       var stdName;  
    
       var stdAge;  
    
       var stdRoll_nu;  
    
         
    
       // Class Function  
    
        showStdInfo() {  
    
            print("Student Name is : ${stdName}");  
    
            print("Student Age is : ${stdAge}");  
    
            print("Student Roll Number is : ${stdRoll_nu}")  
    
    }  

    In the above example of class, we declared a class called Student. This class has three fields stdName, stdAge, and stdRoll_nu. The showStdInfo() is a class function which prints the fields of class. To access the properties of the class, we need to create its object.

    Dart Object

    Dart is object-oriented programming, and everything is treated as an object in Dart. An object is a variable or instance of the class used to access the class’s properties. Objects have two features – state and behavior. Suppose a man is an object with a state (name, age, health) and behavior (walking, running, and sleeping). Programming objects are theoretically similar to the real-life objects; they also have state and behavior. An object is created from a template which is known as class.

    The fields of the classes are stored as object states, whereas the method represents an object’s behavior.

    Creating Class Objects in Dart

    After creating the class, we can create an instance or object of that class which we want to access its fields and functions. The new keyword is used to declare class followed by the class name. The general syntax of creating an object of a class is given below.

    Syntax:

    var object_name  = new class_name(<constructor_arguments>);  

    Here, object_name and class_name signifies as the actual object name and class name respectively. If the class constructor is parameterized then constructor arguments must be passed value.

    Let’s understand the following example.

    Example –

    // Defining class  
    
     class Student {  
    
       var stdName;  
    
       var stdAge;  
    
       var stdRoll_nu;  
    
         
    
       // Class Function  
    
        showStdInfo() {  
    
            print("Student Name is : ${stdName}");  
    
            print("Student Age is : ${stdAge}");  
    
            print("Student Roll Number is : ${stdRoll_nu}")  
    
      
    
    }  
    
    }  
    
    void main () {  
    
     // Creating Object called std  
    
      var std = new Student();  
    
    }  

    We have created the object called std of the class Student but only creating an object not enough. We have to access the properties by using the newly created object.

    Assessing Instance Variable and Function

    After creating an object, we can access the fields and methods of the class. The class property name is separated by the (.) operator with the instance name. The syntax is given below.

    Syntax:

    objectName.propName or objectName.methoName()  

    Let’s understand the following example.

    Example –

    // Defining class  
    
     class Student {  
    
       var stdName;  
    
       var stdAge;  
    
       var stdRoll_nu;  
    
         
    
       // defining class function  
    
        showStdInfo() {  
    
            print("Student Name is : ${stdName}");  
    
            print("Student Age is : ${stdAge}");  
    
            print("Student Roll Number is : ${stdRoll_nu}");  
    
      
    
                   }  
    
    }  
    
    void main () {  
    
      
    
      // Creating object called std  
    
      var std = new Student();  
    
      std.stdName = "Peter";  
    
      std.stdAge =24;  
    
      std.stdRoll_nu = 90001;  
    
    // Accessing class Function  
    
     std.showStdInfo();  
    
    } 

    Output

    Student Name is: Peter
    Student Age is: 24
    Student Roll Number is: 90001
    

    Explanation:

    In the above example, we created a class called Student, which consisted of the student name, age, roll number, and showStdInfo() function to show the student details.

    Then, we created a Student class object and assigned the values to each field by using the (.) operator. We called the showStdInfo() function that displayed the details as an output to screen.

    Benefit 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.
  • Object-Oriented Concepts

    Dart is an object-oriented programming language, and it supports all the concepts of object-oriented programming such as classes, object, inheritance, mixin, and abstract classes. As the name suggests, it focuses on the object and objects are the real-life entities. The Object-oriented programming approach is used to implement the concept like polymorphism, data-hiding, etc. The main goal of oops is to reduce programming complexity and do several tasks simultaneously. The oops concepts are given below.

    • Class
    • Object
    • Inheritance
    • Polymorphism
    • Interfaces
    • Abstract class

    Below is the brief introduction of these oops concepts.

    Class

    Dart classes are defined as the blueprint of the associated objects. A Class is a user-defined data type that describes the characteristics and behavior of it. To get all properties of the class, we must create an object of that class. The syntax of the class is given below.

    Syntax:

    class ClassName {  
    
        <fields>  
    
        <getter/setter>     
    
        <constructor>  
    
        <functions>  
    
    } 

    Object

    An object is a real-life entity such as a table, human, car, etc. The object has two characteristics – state and behavior. Let’s take an example of a car which has a name, model name, price and behavior moving, stopping, etc. The object-oriented programming offers to identify the state and behavior of the object.

    We can access the class properties by creating an object of that class. In Dart, The object can be created by using a new keyword followed by class name. The syntax is given below.

    Syntax:

    var objectName = new ClassName(<constructor_arguments>)  

    Inheritance

    Dart supports inheritance, which is used to create new classes from an existing class. The class that to be extended is called parent /superclass, and the newly created class is called child/subclass. Dart provides extends keyword to inherit the properties of parent class in child class. The syntax is given below.

    Syntax:

    class child_class_name extends parent_class_name   

    Polymorphism

    Polymorphism is an object-oriented programming concept where one thing has many forms. It can be two types – Runtime polymorphism and Compile time polymorphism. For example – A function has the same name but with a different behavior or class. Another example is the shape() class, and all the class inherited from the Rectangle, Triangle, and circle.

    Interfaces

    The interface is defined as a blueprint of the class. We can declare methods and variables inside the interface just like the class but in interface only abstract declaration of methods is provided. We can only define the function signature but not its body. Another class can implement the interface. It is basically used for data-hiding.

    Abstract Class

    A class that contains one or more abstract method is called an abstract class. We can declare the abstract class using the abstract keyword followed by class declaration. The syntax is given below.

    Syntax:

    abstract class ClassName {  
    
      //Body of abstract class  
    
    }

    The above introductions give the basic idea of oops concepts. We will have a detailed discussion in upcoming tutorials.