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
- Class: A template that defines the structure and behavior of the object.
- 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.
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.
Explanation:
- Class
Car
:- It has two properties:
brand
andmodel
. - 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.
- It has two properties:
- Creating an Object:
- In the
main()
function, we create an objectmyCar
of theCar
class using the constructorCar('Toyota', 'Corolla')
. - The
displayInfo()
method is called on the objectmyCar
to print its details.
- In the
Output:
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.
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.
- The getter
- 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:
Key Points to Remember:
- Classes are the blueprint or template for creating objects in Dart.
- Objects are instances of classes, and each object has its own state (data) and behavior (methods).
- Constructors are special methods used to initialize objects.
- Methods define the behaviors of the objects.
- Encapsulation can be used to restrict access to the data through getters and setters.
- 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.