What is class?
A class in terms of OOP is a blueprint for creating objects. A class encapsulates data for the object. Dart gives built-in support for this concept called class.
Syntax of declaring class:
class class_name {
<fields>
<getters/setters>
<constructors>
<functions>
}
A class definition can include the following −
- Fields − A field is any variable declared in a class. Fields represent data pertaining to objects.
- Setters and Getters − Allows the program to initialize and retrieve the values of the fields of a class. A default getter/ setter is associated with every class. However, the default ones can be overridden by explicitly defining a setter/ getter.
- Constructors − responsible for allocating memory for the objects of the class.
- Functions − Functions represent actions an object can take. They are also at times referred to as methods.
These components put together are termed the data members of the class.
Example: Declaring a class
class Car {
// field
String engine = "E1001";
// function
void disp() {
print(engine);
}
}
Example: Instantiating a class
var obj = new Car("Engine 1")
Accessing Attributes and Functions
A class’s attributes and functions can be accessed through the object. Use the ‘.’ dot notation (called as the period) to access the data members of a class.
//accessing an attribute
obj.field_name
//accessing a function
obj.function_name()
Example:
void main() {
Car c= new Car();
c.disp();
}
class Car {
// field
String engine = "E1001";
// function
void disp() {
print(engine);
}
}
The output of the above code is as follows −
E1001
Defining a Class
In Dart, a class is defined using the class keyword followed by the name of the class. The body of the class is enclosed in curly braces { } and can contain fields, methods, constructors, and other classes.
Here is an example of a simple class definition in Dart:
class Person {
String name;
int age;
void greet() {
print("Hello, my name is $name and I am $age years old.");
}
}
In this example, we define a Person class with two fields, name, and age, and one method, greet(), which prints a greeting to the console.
Creating Objects
Once we have defined a class, we can create objects from it using the new keyword followed by the name of the class and any arguments required by its constructor.
Here is an example of creating an object from the Person class we defined earlier:
var john = new Person();
In this example, we create a new Person object and assign it to a variable named john. By default, the fields of the object are initialized to their default values (null for name and 0 for age).
We can also pass arguments to the constructor when creating objects, like this:
var jane = new Person()
..name = "Jane"
..age = 30;
In this example, we create a new Person object and set its name and age fields using the cascade operator (..).
Accessing Properties and Methods
Once we have created an object, we can access its fields and methods using the dot (.) operator.
Here is an example of accessing the name field and greet() method of a Person object:
print(john.name); // prints "null"
print(jane.name); // prints "Jane"
jane.greet(); // prints "Hello, my name is Jane and I am 30 years old."
In this example, we access the name field of the john object (which is null since we didn’t set it) and the name field and greet() method of the jane object.
Inheritance
One of the key features of OOP is inheritance, which allows us to create new classes that inherit properties and methods from existing classes. In Dart, we can define a subclass by using the extends keyword followed by the name of the superclass.
Here is an example of a Student class that inherits from the Person class:
class Student extends Person {
int grade;
void study() {
print("$name is studying hard for grade $grade.");
}
}
In this example, we define a Student class that extends the Person class and adds a grade field and a study() method.
We can create objects for the Student class just like we did with the Person class, and they will have access to all the properties and methods of both classes:
var bob = new Student()
..name = "Bob"
..age = 20
..
Inheritance is a mechanism in object-oriented programming that allows one class to inherit the properties and methods of another class. In Dart, a class can inherit from another class using the extends keyword.
Example:
class Animal {
String name;
Animal(String name) {
this.name = name;
}
void speak() {
print("Animal speaks");
}
}
class Dog extends Animal {
Dog(String name) : super(name);
void bark() {
print("Woof");
}
@override
void speak() {
print("Dog barks");
}
}
void main() {
var dog = Dog("Buddy");
print(dog.name); // Buddy
dog.bark(); // Woof
dog.speak(); // Dog barks
}
In this example, the Dog class extends the Animal class and inherits the name property and speak() method from the Animal class.
A class inherits from another class using the ‘extends’ keyword.
Types of Inheritance
Inheritance can be of the following three types −
- Single − Every class can at the most extend from one parent class.
- Multiple − A class can inherit from multiple classes. Dart doesn’t support multiple inheritances.
- Multi-level − A class can inherit from another child class.
Classes are an essential part of object-oriented programming (OOP) languages like Dart. They are used to create objects, which are instances of the class, and contain both data and functions. In this tutorial, we will cover the basics of classes in Dart, including how to define them, create objects from them, and access their properties and methods.
Constructors
Constructors in Dart are special methods that create and initialize objects. In a class, a constructor is defined using the same name as the class name.
There are two types of constructors in Dart:
- Default Constructor: A constructor with no parameters is called the default constructor. If no constructor is defined in a class, Dart provides a default constructor that takes no arguments and does nothing.
Example:
class Point {
int x, y;
Point() {
x = 0;
y = 0;
}
}
- Parameterized Constructor: A constructor with one or more parameters is called a parameterized constructor. It allows you to create an object with some initial values.
Example:
class Point {
int x, y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
}
A constructor is a special function of the class that is responsible for initializing the variables of the class. A constructor is a function and hence can be parameterized. However, unlike a function, constructors cannot have a return type. If you don’t declare a constructor, a default no-argument constructor is provided for you.
Example:
void main() {
Car c = new Car('E1001');
}
class Car {
Car(String engine) {
print(engine);
}
}
The output will be-
E1001
- Named Constructors: Dart provides named constructors to enable a class to define multiple constructors.
Example:
void main() {
Car c1 = new Car.namedConst('E1001');
Car c2 = new Car();
}
class Car {
Car() {
print("Non-parameterized constructor invoked");
}
Car.namedConst(String engine) {
print("The engine is : ${engine}");
}
}
The output will be-
The engine is : E1001
Non-parameterized constructor invoked
Getters and Setters, also called accessors and mutators, allow the program to initialize and retrieve the values of class fields respectively. Getters or accessors are defined using the get keyword. Setters or mutators are defined using the set keyword.
A default getter/setter is associated with every class. However, the default ones can be overridden by explicitly defining a setter/ getter. A getter has no parameters and returns a value, and the setter has one parameter and does not return a value.
Abstract Classes
An abstract class is a class that cannot be instantiated. It is used as a base class for other classes to inherit from. To create an abstract class in Dart, use the abstract keyword.
Example:
abstract class Shape {
void draw();
}
class Circle extends Shape {
@override
void draw() {
print("Drawing Circle");
}
}
void main() {
var circle = Circle();
circle.draw(); // Drawing Circle
}
In this example, the Shape class is an abstract class that defines the draw() method. The Circle class extends the Shape class and implements the draw() method.
Interfaces
In Dart, you can define an interface using an abstract class. An interface defines a set of methods that a class must implement. To implement an interface, use the implements keyword.
Example:
abstract class Shape {
void draw();
}
class Circle implements Shape {
@override
void draw() {
print("Drawing Circle");
}
}
void main() {
var circle = Circle();
circle.draw(); // Drawing Circle
}
In this example, Shape is an interface that defines the draw() method. The Circle class implements the Shape interface and provides the implementation for the draw() method.
Mixins
A mixin is a way of reusing a class’s code in multiple class hierarchies. A mixin is defined using the keyword.
Example:
class Logger {
void log(String message) {
print("Logging: $message");
}
}
class Circle with Logger {
void draw() {
log("Drawing Circle");
}
}
class Square with Logger {
void draw() {
log("Drawing Square");
}
}
void main() {
var circle = Circle();
circle.draw(); // Output: Logging: Drawing Circle
var square = Square();
square.draw(); // Output: Logging: Drawing Square
}
Output:
Logging: Drawing Circle
Logging: Drawing Square
Example:
class Musician {
void play() {
print("Playing music…");
}
}
class Singer {
void sing() {
print("Singing…");
}
}
class Performer with Musician, Singer {
void perform() {
play();
sing();
print("Performing…");
}
}
void main() {
var performer = Performer();
performer.perform();
}
Output:
In the main() function, we create an instance of the Performer class and call its perform() method. This results in the output:
Playing music…
Singing…
Performing…
In this example, we define three classes: Musician, Singer, and Performer. Musician and Singer are mixin classes, which means they provide additional functionality to the Performer class. The Performer class uses the keyword to combine the Musician and Singer mixin classes.
The Performer class defines a method called the perform() that calls the play() and sing() methods from the Musician and Singer mixin classes, respectively. It also prints a message to indicate that the performer is performing.