Object Oriented Programming in Dart

This blog provides a comprehensive guide to Object-Oriented Programming in Dart. It discusses concepts like Classes, Objects, Inheritance, Polymorphism, and Encapsulation, providing examples and outlining the benefits of each.

GraphQL has a role beyond API Query Language- being the backbone of application Integration
background Coditation

Object Oriented Programming in Dart

Object Oriented Programming is a programming paradigm that believes in grouping data (properties) and methods (actions) together inside a box. It demonstrates the pattern of real-world objects.

Dart OOP features

Dart supports all the features for Object-oriented programing paradigm like Classes, Inheritance, Interfaces, Polymorphism, etc. Inheritance in Dart might seem a little weird but apart from that, everything is alright.
Various OOP features can be implemented in dart. They are:

  • Class
  • Objects
  • Inheritance
  • Polymorphism
  • Encapsulation

Classes

Class is a user defined data type and it contains its own data members(Constructors , fields, getters and setters) and member functions. A class encapsulates data for the object.
A class in Dart can be declared by using the keyword class followed by the class name and the body of the class should be enclosed with a pair of curly braces {}
Dart classes do not support constructor overloading, but you can use the flexible function argument specifications from the language (optional, positional, and named) to provide different ways to instantiate a class. Also, you can have named constructors to define alternatives.

Declaring class in Dart:


class Class_name {
// Body of class
  <constructors>
  <functions>
  <fields>
}

Creating objects 

Like most OOP languages, Dart supports the keyword new for creating instances of classes. Here is an example of a traditional object instantiation, using the new keyword:


class User{
final String name;
 final int age; .
 User(this.name, this.age); 
}
final user = new User('Rahul', 25); Unnecessary new keyword.

As you can see, flutter SDK gives us hints that we can omit the new keyword. Which means you can create object instances without using the new keyword.

Objects

Objects are basic building blocks of a Dart program. An object is a combination of data and methods. 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.

All created objects implicitly inherit from the base objects: the Object.

Some Benefit of Objects

Modularity: The source code of an object can be maintained individually and can hide from the other object's source code.

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 aren't familiar with the internal implementation.

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.

Inheritance

Inheritance allows you to define a class that extends the functionality of another class.With the help of Inheritance, one class can make use of all the properties and characteristics of parent class i.e base class. Dart supports single inheritance. It means that a class can inherit from a single class. Dart doesn’t support multiple inheritances. In other words, a class cannot inherit from two or more classes. To define a class that inherits from another class, you use the extends keyword as follows:


class ParentClass {
 // parant class body 
}
class ChildClass extends ParentClass { 
// child class body
}

The child class will have all properties and methods of the parent class. Also, it can extend the parent class by either overriding the methods from the parent class or having more methods in the child class.

Example:


class Sports {
  final String name;
  const Sports({this.name = ''});

    void score(int count){ 
        print("${count} point scored!");
    }

     void win(){
        print("${name}: Game Won!");
    }
}

class Cricket extends Sports {
  Cricket() : super(name: 'Cricket Format');
  void gameFormat(String format) {
    print("${format} Cricket");
  }
}

class Badminton extends Sports {
  Badminton() : super(name: 'Badminton');
  
  startService() {
     print("Service started!");
  }
}
void main() {
  var cricket = Cricket();
  cricket.gameFormat("T20");
  cricket.score(4);
  cricket.win();
  print(“--------------------------------”);
  var badminton = Badminton();
  badminton.startService();
  badminton.score(1);
  badminton.win();
}


Output: 

T20 Cricket
4 point scored!
Cricket Format: Game Won!
—---------------------------------
Service started!
1 point scored!
Badminton: Game Won!

Polymorphism

Polymorphism is an essential concept in an object-oriented programming language. In polymorphism, an object can take multiple forms. As the word suggests, poly means many and morph means forms, hence, polymorphism means having multiple forms. Polymorphism is generally used to achieve the inheritance mechanism.
Polymorphism in Dart is supported only in the form of runtime polymorphism (For example, method overriding). Subclasses usually override instance methods, getters, and setters. We can use the @override annotation to indicate that we’re overriding a member.

Features of Polymorphism

  • The functionality of a method behaves differently in different scenarios.
  • It allows the same name for a member or method in a class with different data types.
  • The behavior of a method depends on the data provided.
  • Polymorphism supports implicit type conversion..

Advantage Of Polymorphism In Dart

  • Subclasses can override the behavior of the parent class.
  • It allows us to write code that is more flexible and reusable.
  • Reusable code
  • Reduces coupling between different functionalities.

Polymorphism By Method Overriding In Dart

In this example below, there is a class named Employee with a method named salary(). The salary() method is overridden in two child classes named Manager and Developer.


class Employee {
 	void salary() { 
print("Employee salary is \$2000."); 
}
}
class Manager extends Employee {
  @override
  void salary(){
    print("Manager salary is \$5000.");
  }
}
class Developer extends Employee {
  @override 
  void salary() {
    print("Developer salary is \$4000.");
  }
}
void main{
 Manager manager = Manager();
 Developer developer = Developer();
 manager.salary();
 developer.salary();
}


Output: 

Manager salary is $5000.
Developer salary is $4000

In the above example, the @override annotation means the method is overridden from the parent class. Here the method salary() in the Manage and Developer class is overridden by the parent class Employee.

Encapsulation

Encapsulation is the principle that limits access to an object's state; and the bundling of methods and operations that do work on a set of data.
The whole idea behind encapsulation is to hide the implementation details from users. 
If a data member is private it means it can only be accessed within the same class. No outside class can access private data members of other classes. 
However if we set up public getter and setter methods to update the private data fields then the outside class can access those private data fields via public methods.

Benefits of Encapsulation

  • Data Hiding: The users will have no idea about the implementation details of the class. It will not be visible to the user how the class is storing the values. The user will only know that values are being passed and initialized.
  • More Flexibility: We can make the variables of the class read-only or write-only according to our requirements. If we want to make the variables read-only then we have to use the setter methods like setName(), SetAge(), etc, and if we want to make the variables write only then we need to use the getter methods like getName(), getValue(), etc from the program.
  • Reusability: Encapsulation also provides the feature of code reusability and is easy to change with newer requirements.
  • Easy Testing: The encapsulated code is easy to test for unit testing.

In conclusion, Dart, a robust and flexible programming language, offers strong support for object-oriented programming. It allows developers to create structured, scalable, and readable code by leveraging core concepts such as classes, objects, inheritance, polymorphism, and encapsulation. These features, widely used in real-world applications, offer several benefits such as code reusability, modularity, data hiding, and improved testing capabilities, we discussed the concepts like Classes, Objects, Inheritance, Polymorphism, and Encapsulation, with examples and outlining the benefits of each.

In our next blog, we discuss JavaScript, its prototype-based nature, and how it supports object-oriented and functional programming patterns.

Hi, I am Manish Dube. I am a Javascript & Flutter developer with over 6 years of experience in software development. In my free time, I enjoy playing outdoor games and staying up-to-date with the latest developments in the tech industry.

Want to receive update about our upcoming podcast?

Thanks for joining our newsletter.
Oops! Something went wrong.