Introduction to Classes and Objects in Dart

Ideally 55-60 characters

Dec 28, 2023

Understanding Classes in Dart

A class in Dart is a blueprint for creating objects. It's a user-defined data type that holds its own data members and member functions, which can be accessed and used by creating an instance of that class. A class encapsulates data for the object.
Basic Class Structure:
class Person { String name; int age; Person(this.name, this.age); void greet() { print("Hello, my name is $name and I am $age years old."); } }
In this example, Person is a class with two data members (name and age) and one method (greet).

Creating Objects

An object is an instance of a class. When a class is defined, no memory is allocated until an object of that class is created.
Creating an Instance:
var person1 = Person("Alice", 30); person1.greet(); // Outputs: Hello, my name is Alice and I am 30 years old.
Here, person1 is an object of the Person class.

Constructors

Constructors are special methods of a class that are called when a new object of that class is created. Dart allows named constructors and even constructor forwarding.
Example with Constructor:
class Person { String name; int age; Person(this.name, this.age); // Constructor }

Named Constructors

Dart provides the concept of "named constructors" to enable a class to define multiple constructors.
Example of Named Constructor:
class Person { String name; int age; Person(this.name, this.age); // Named constructor Person.guest() { name = 'Guest'; age = 18; } } var guest = Person.guest();

Inheritance in Dart

Inheritance is a mechanism where a new class is derived from an existing class. The derived class is called a child class or subclass, and the existing class is known as the parent or superclass.
Basic Inheritance:
class Employee extends Person { double salary; Employee(String name, int age, this.salary) : super(name, age); }

The Role of Objects

Objects are fundamental to Dart. They are instances of classes and hold the actual data. When you define a class, you define a blueprint for an object. Using that blueprint (class), you can create as many objects as you need.

Summary

Classes and objects are core concepts in Dart programming. A class provides the structure for an object, while an object is an instance of a class. Understanding these concepts is crucial for anyone looking to develop applications using Dart, as they form the basis of object-oriented programming within the language.