Dart Classes and Objects


Classes and Objects in Dart

In Dart, classes are blueprints or templates for creating objects. They define the properties (fields) and behaviors (methods) that the objects created from them will have. Objects are instances of a class, created based on the class blueprint. When you instantiate a class, you create an object that can hold data and perform actions defined in the class.

Key Concepts

  1. Class: A template that defines the structure and behavior of the object.
  2. Object: An instance of a class. It holds specific data and can invoke methods defined in the class.

Syntax of a Class in Dart

A class in Dart is defined using the class keyword, followed by the class name and a body containing fields and methods.

class ClassName { // Fields type fieldName; // Constructor ClassName(parameters); // Methods returnType methodName() { // code } }

Example: Basic Class and Object in Dart

Let’s define a class Car that has two fields: brand and model. The class will also have a method displayInfo() to show the car's details.

class Car { // Fields (Properties) String brand; String model; // Constructor to initialize the fields Car(this.brand, this.model); // Method to display car information void displayInfo() { print('Brand: $brand, Model: $model'); } } void main() { // Creating an object (instance) of the Car class var myCar = Car('Toyota', 'Corolla'); // Accessing method using the object myCar.displayInfo(); // Output: Brand: Toyota, Model: Corolla }

Explanation:

  • Class Car:
    • It has two properties: brand and model.
    • The constructor Car(this.brand, this.model) is used to initialize the values of the properties.
    • The method displayInfo() is used to print the car's details.
  • Creating an Object:
    • In the main() function, we create an object myCar of the Car class using the constructor Car('Toyota', 'Corolla').
    • The displayInfo() method is called on the object myCar to print its details.

Output:

Brand: Toyota, Model: Corolla

More Advanced Example: Adding Getters, Setters, and Methods

Let’s now expand the class to include getter and setter methods for encapsulation, allowing controlled access to the private fields.

class BankAccount { // Private fields (Encapsulation) double _balance = 0.0; String _owner; // Constructor BankAccount(this._owner, this._balance); // Getter for balance double get balance => _balance; // Setter for balance set balance(double amount) { if (amount >= 0) { _balance = amount; } else { print('Invalid amount'); } } // Method to deposit money void deposit(double amount) { if (amount > 0) { _balance += amount; print('Deposited: \$${amount}'); } else { print('Invalid deposit amount'); } } // Method to withdraw money void withdraw(double amount) { if (amount > 0 && _balance >= amount) { _balance -= amount; print('Withdrew: \$${amount}'); } else { print('Insufficient funds or invalid withdrawal amount'); } } // Method to display account info void displayAccountInfo() { print('Account Owner: $_owner'); print('Balance: \$$_balance'); } } void main() { // Creating an object of the BankAccount class var account = BankAccount('John Doe', 1000.0); // Accessing methods and properties account.displayAccountInfo(); // Output: Account Owner: John Doe, Balance: $1000.0 account.deposit(500.0); // Output: Deposited: $500.0 account.withdraw(200.0); // Output: Withdrew: $200.0 account.balance = 1500.0; // Using setter print('Updated Balance: \$${account.balance}'); // Output: Updated Balance: $1500.0 account.displayAccountInfo(); // Output: Account Owner: John Doe, Balance: $1500.0 }

Explanation:

  • Private fields: The _balance and _owner fields are private (indicated by the leading underscore _), which means they cannot be accessed directly outside the class.
  • Getter and Setter:
    • The getter balance allows access to the _balance field.
    • The setter balance ensures that the balance cannot be set to a negative value.
  • Methods:
    • deposit() adds money to the account if the amount is valid.
    • withdraw() subtracts money from the account if the balance is sufficient.
    • displayAccountInfo() shows the account details.

Output:

Account Owner: John Doe Balance: $1000.0 Deposited: $500.0 Withdrew: $200.0 Updated Balance: $1500.0 Account Owner: John Doe Balance: $1500.0

Key Points to Remember:

  1. Classes are the blueprint or template for creating objects in Dart.
  2. Objects are instances of classes, and each object has its own state (data) and behavior (methods).
  3. Constructors are special methods used to initialize objects.
  4. Methods define the behaviors of the objects.
  5. Encapsulation can be used to restrict access to the data through getters and setters.
  6. Object-oriented concepts like inheritance, polymorphism, and abstraction can be applied to make your code more modular, reusable, and maintainable.

By following these principles, you can create robust, maintainable, and scalable applications in Dart.