In this post, we will explore the object oriented concept of a class in Dart language. We will go in depth on topics such as constructors, abstract class, and private/public identifiers.
Introduction
In object oriented programming, a class is the most important basic building block. It represents a blueprint for creating data structure. It encapsulates the properties and operations that any object can have.
If you are completely new to the concept of a class and object oriented programming, you should do some more reading from here.
How To Define A Class
Creating a class in Dart is quite easy. The basic syntax is:
class class_name {
}
So, if we are creating a class for a Car object, it would look something like this:
class Car {
void start() {
}
void shutDown() {
}
bool isRunning;
}
Creating Objects From Class
In Dart, the new
keyword is optional when creating an object of a class.
var car1 = Car();
var car2 = new Car();
//both are valid
Class Constructor In Dart
The class constructor is a special type of function of the class which allows initializing properties or doing any operation during the time of object creation. We can pass parameters on the constructor function.
By default, if no constructor is defined, a no-argument constructor is assumed.
class Car {
int id;
Car(int id) {
//init id here...
}
void start() {
}
...
..
}
In the code above, we have a constructor that takes a single parameter which is an integer value.
//creating object of Car with constructor
var car = Car(1);
How many constructors can a class have in Dart?
By default, we can have only one constructor for any class. However, Dart also has Named Constructors
which can be used to enable defining multiple constructors.
Named Constructor
Here we have a named constructor fromName
for Animal
class.
class Animal {
Animal(int id) {
print(id);
}
Animal.fromName(String name) {
print(name);
}
}
To create object of class from the Named Constructor
, we can do this:
var car2 = Car.fromName('Everest');
Abstract Class
As the name suggests, an abstract class is a class which has not been completely defined. It is abstract. Similar to an interface in OOP, you can define signature of functions and properties for a class with abstract class.
An abstract class is declared with the abstract
keyword.
abstract class Human {
void walk();
}
You can not directly instantiate an abstract class.
//can't do this.
var human = Human();
Any other class can implement the abstract
class.
class Boy implements Human {
@override
void walk() {
//do your thing
}
}
Learn more about implementing and extending class behaviors in Dart from here.
A Private Class In Dart
A private class by definition has limited accessibility. It is private to the library where it is defined and cannot be accessed from anywhere else.
In Dart, we separate a private class from a public class by the help of the underscore(_) keyword.
class _Book {
//..
}