What is a Class?
In Dart, a class is a blueprint or template that defines the properties (variables) and behaviors (methods) of an object.
It's like a blueprint for creating houses: the class defines the number of rooms, the size of the kitchen, the type of windows, etc.
Objects, on the other hand, are specific instances created from this class. Think of them as individual houses built according to the blueprint.
Key Concepts:
Objects: Instances of a class.
Properties: Variables that define the characteristics of an object.
Methods: Functions that define the behaviour of an object.
Constructor: A special method to initialize an object.
class Car
{
String model;
int year;
// Constructor (special method to initialize objects)
Car(this.model, this.year);
void drive()
{
print('Driving $model');
}
}
void main()
{
// Create objects (instances) of the Car class
Car myCar = Car('Toyota Camry', 2023);
Car friendCar = Car('Honda Civic', 2022);
// Access properties
print('My car model: ${myCar.model}');
print('Friend\'s car year: ${friendCar.year}');
// Call methods
myCar.drive();
friendCar.drive();
}
Class Definition:
We define a class named Car.
Inside the class, we declare two properties:
model (String): to store the car model.
year (int): to store the manufacturing year.
We define a method named drive() that prints a message when called.
Constructor:
The Car(this.model, this.year) is a constructor.
It's a special method that is automatically called when you create an object of the class.
this.model and this.year are shorthand for assigning the provided values to the model and year properties of the object.
Object Creation:
Car myCar = Car('Toyota Camry', 2023); creates an object named myCar of the Car class.
Car friendCar = Car('Honda Civic', 2022); creates another object named friendCar.
Accessing Properties:
myCar.model and friendCar.year access the model property of myCar and the year property of friendCar, respectively.
Calling Methods:
myCar.drive() and friendCar.drive() call the drive() method on the respective objects.
void main()
{
var student1=Student(); //object of class Student
print('${student1.id} and ${student1.name}');
}
//In Class- Define states(Properties) and behaviour of a student
class Student
{
int? id; //property of Student
String? name; //property of Student
void study() //Behaviour of Student
{
}
void sleep() //Behaviour of Student
{
}
}
void main()
{
var student1=Student();
student1.id=1;
student1.name='Sandeep';
print('${student1.id} and ${student1.name}');
student1.study(); //calling behavour/method
student1.sleep(); //calling behavour/method
}
//In Class- Define states(Properties) and behaviour of a student
class Student
{
int? id; //property of Student
String? name; //property of Student
void study() //Behaviour of Student
{
print('${this.name} is now studing');
}
void sleep() //Behaviour of Student
{
print('${this.name} will sleeping after 1 hour ');
}
}
---------------------------------------------------------------------
1. Simple Class with Properties and Methods
class Rectangle
{
double width;
double height;
Rectangle(this.width, this.height);
double calculateArea() {
return width * height;
}
double calculatePerimeter() {
return 2 * (width + height);
}
}
void main() {
Rectangle rect = Rectangle(5.0, 3.0);
print('Area: ${rect.calculateArea()}');
print('Perimeter: ${rect.calculatePerimeter()}');
}
-------------------------------------------------------------
void main()
{
var student1=Student(); //one object, student1 is refrence varible
student1.id=1;
student1.name='Sandeep';
print('${student1.id} and ${student1.name}');
student1.study(); //calling behavour/method
student1.sleep(); //calling behavour/method
var student2=Student(); //one object, student2 is refrence varible
student2.id=2;
student2.name='Pradeep';
student2.age=23;
print('${student2.id} and ${student2.name}');
student2.study();
student2.sleep();
student2.intro();
}
//In Class- Define states(Properties) and behaviour of a student
class Student
{
int? id; //property of Student (instance or field variable)
String? name; //property of Student (instance or field variable)
int? age;
void study() //Behaviour of Student
{
print('${this.name} is now studing');
}
void sleep() //Behaviour of Student
{
print('${this.name} will sleeping after 1 hour ');
}
void intro()
{
print('${this.name} has age 24');
}
}
A simple program that creates a Person class with a name and age, and prints a greeting.
class Person {
String name;
int age;
Person(this.name, this.age); //constructure
void greet() {
print("Hello, my name is $name and I am $age years old.");
}
}
void main() {
Person person = Person("Alice", 25);
person.greet();
}
A program with a constructor that provides default values if no values are passed.
class Car {
String brand;
int year;
Car({this.brand = "Toyota", this.year = 2020}); //default constructor
void displayInfo() {
print("Brand: $brand, Year: $year");
}
}
void main() {
Car car1 = Car();
Car car2 = Car(brand: "Honda", year: 2022);
car1.displayInfo();
car2.displayInfo();
}
A program that uses getter and setter methods to access private fields.
class Rectangle {
double _width;
double _height;
Rectangle(this._width, this._height);
double get area => _width * _height;
set width(double value) => _width = value;
set height(double value) => _height = value;
}
void main() {
Rectangle rect = Rectangle(5.0, 4.0);
print("Area: ${rect.area}");
rect.width = 6.0;
print("New Area: ${rect.area}");
}
A program demonstrating inheritance with a parent Animal class and a child Dog class.
class Animal {
void sound() {
print("Animal makes a sound.");
}
}
class Dog extends Animal {
@override
void sound() {
print("Dog barks.");
}
}
void main() {
Dog dog = Dog();
dog.sound();
}
A program that overrides a parent method in the child class.
class Vehicle {
void start() {
print("Vehicle starting...");
}
}
class Car extends Vehicle {
@override
void start() {
print("Car starting with a roar...");
}
}
void main() {
Vehicle vehicle = Car();
vehicle.start();
}
A program using an abstract class with abstract and concrete methods.
abstract class Shape {
void draw(); // Abstract method
void printShape() {
print("This is a shape.");
}
}
class Circle extends Shape {
@override
void draw() {
print("Drawing a circle.");
}
}
void main() {
Circle circle = Circle();
circle.printShape();
circle.draw();
}
A program using an interface to define behavior that different classes can implement.
class Printable {
void printDetails();
}
class Book implements Printable {
String title;
Book(this.title);
@override
void printDetails() {
print("Book title: $title");
}
}
void main() {
Printable printable = Book("Dart Programming");
printable.printDetails();
}
A program using named constructors to create different types of objects from the same class.
class Student {
String name;
int age;
Student(this.name, this.age);
// Named constructor
Student.fromHighSchool() : name = "High School Student", age = 16;
Student.fromUniversity() : name = "University Student", age = 20;
void displayInfo() {
print("Name: $name, Age: $age");
}
}
void main() {
Student student1 = Student.fromHighSchool();
Student student2 = Student.fromUniversity();
student1.displayInfo();
student2.displayInfo();
}
A program that uses encapsulation by making variables private and using getters and setters.
class BankAccount {
double _balance;
BankAccount(this._balance);
double get balance => _balance;
void deposit(double amount) {
_balance += amount;
}
void withdraw(double amount) {
if (amount <= _balance) {
_balance -= amount;
} else {
print("Insufficient funds.");
}
}
}
void main() {
BankAccount account = BankAccount(1000.0);
account.deposit(500.0);
account.withdraw(300.0);
print("Balance: ${account.balance}");
}
A program that demonstrates the use of static variables and methods in a class.
class MathUtils {
static const double pi = 3.14159;
static double areaOfCircle(double radius) {
return pi * radius * radius;
}
}
void main() {
print("PI: ${MathUtils.pi}");
print("Area of circle with radius 5: ${MathUtils.areaOfCircle(5)}");
}
These programs cover basic principles of classes, objects, encapsulation, inheritance, polymorphism, abstraction, and static members in Dart. Each example provides a glimpse into how Dart handles these object-oriented concepts.
Basic class definition and constructors.
Inheritance and method overriding.
Getter, setter, and factory constructors.
Polymorphism, interfaces, and abstract classes.
Static methods, instance methods, and collections.
Enums and event handling in object-oriented design
class Person {
String name;
int age;
Person(this.name, this.age);
void introduce() {
print("Hi, my name is $name and I am $age years old.");
}
}
void main() {
var person = Person("Alice", 25);
person.introduce(); // Output: Hi, my name is Alice and I am 25 years old.
}
class Rectangle {
double width;
double height;
// Constructor 1
Rectangle(this.width, this.height);
// Constructor 2 (named constructor)
Rectangle.square(double size) : width = size, height = size;
double area() => width * height;
}
void main() {
var rect1 = Rectangle(5, 10);
var square = Rectangle.square(4);
print("Area of rectangle: ${rect1.area()}"); // Output: 50
print("Area of square: ${square.area()}"); // Output: 16
}
class Circle {
double radius;
Circle(this.radius);
// Getter
double get area => 3.14 * radius * radius;
// Setter
set radiusValue(double value) {
if (value > 0) {
radius = value;
} else {
print("Radius cannot be negative.");
}
}
}
void main() {
var circle = Circle(5);
print("Area: ${circle.area}"); // Output: 78.5
circle.radiusValue = 10;
print("Updated Area: ${circle.area}"); // Output: 314.0
}
class Animal {
void speak() {
print("Animal makes a sound.");
}
}
class Dog extends Animal {
@override
void speak() {
print("Dog barks.");
}
}
void main() {
var dog = Dog();
dog.speak(); // Output: Dog barks.
}
class Employee {
void work() {
print("Employee is working.");
}
}
class Manager extends Employee {
@override
void work() {
print("Manager is managing the team.");
}
}
void main() {
var manager = Manager();
manager.work(); // Output: Manager is managing the team.
}
class Shape {
void draw() {
print("Drawing a shape.");
}
}
class Circle extends Shape {
@override
void draw() {
print("Drawing a circle.");
}
}
void main() {
Shape shape = Circle();
shape.draw(); // Output: Drawing a circle.
}
abstract class Vehicle {
void start(); // Abstract method
}
class Car extends Vehicle {
@override
void start() {
print("Car is starting.");
}
}
void main() {
var car = Car();
car.start(); // Output: Car is starting.
}
class Animal {
void sound();
}
class Cat implements Animal {
@override
void sound() {
print("Meow");
}
}
void main() {
var cat = Cat();
cat.sound(); // Output: Meow
}
class MathUtility {
static int add(int a, int b) {
return a + b;
}
}
void main() {
print(MathUtility.add(5, 3)); // Output: 8
}
class Student {
String name;
int grade;
Student(this.name, this.grade);
}
void main() {
var students = [
Student("Alice", 90),
Student("Bob", 85),
Student("Charlie", 95)
];
for (var student in students) {
print("${student.name}: ${student.grade}");
}
}
class Point {
double x, y;
// Constructor with default values
Point([this.x = 0, this.y = 0]);
void display() {
print("Point is at ($x, $y)");
}
}
void main() {
var p1 = Point();
var p2 = Point(2, 3);
p1.display(); // Output: Point is at (0.0, 0.0)
p2.display(); // Output: Point is at (2.0, 3.0)
}
class Shape {
String type;
// Named factory constructor
Shape._(this.type);
factory Shape.circle() {
return Shape._("Circle");
}
factory Shape.square() {
return Shape._("Square");
}
void display() {
print("This is a $type.");
}
}
void main() {
var shape1 = Shape.circle();
var shape2 = Shape.square();
shape1.display(); // Output: This is a Circle.
shape2.display(); // Output: This is a Square.
}
class Employee {
String name;
int id;
Employee(this.name, this.id);
Map<String, dynamic> toJson() {
return {
'name': name,
'id': id,
};
}
}
void main() {
var emp = Employee("Alice", 101);
print(emp.toJson()); // Output: {name: Alice, id: 101}
}
class Outer {
String name;
Outer(this.name);
class Inner {
void display() {
print("This is an inner class.");
}
}
}
void main() {
var outer = Outer("Outer Class");
var inner = outer.Inner();
inner.display(); // Output: This is an inner class.
}
class Counter
{
int _count = 0; // Instance variable
static int staticCount = 0; // Static variable
void increment() {
_count++;
staticCount++;
}
void display() {
print("Instance count: $_count");
print("Static count: $staticCount");
}
}
void main() {
var counter1 = Counter();
var counter2 = Counter();
counter1.increment();
counter2.increment();
counter1.display();
counter2.display();
}
class Book {
String title;
String author;
Book(this.title, this.author);
void display() {
print("$title by $author");
}
}
void main() {
var books = [
Book("1984", "George Orwell"),
Book("To Kill a Mockingbird", "Harper Lee")
];
for (var book in books) {
book.display();
}
}
class CollectionExample {
Set<int> numbers;
CollectionExample() : numbers = {};
void addNumber(int number) {
numbers.add(number);
}
void displayNumbers() {
print(numbers);
}
}
void main() {
var collection = CollectionExample();
collection.addNumber(1);
collection.addNumber(2);
collection.addNumber(2);
collection.displayNumbers(); // Output: {1, 2}
}
class Calculator {
double add(double a, double b) => a + b;
double subtract(double a, double b) => a - b;
double multiply(double a, double b) => a * b;
double divide(double a, double b) => a / b;
}
void main() {
var calc = Calculator();
print(calc.add(10, 5)); // Output: 15
print(calc.subtract(10, 5)); // Output: 5
}
enum Status { Active, Inactive }
class User {
String name;
Status status;
User(this.name, this.status);
void display() {
print("User: $name, Status: ${status.toString().split('.').last}");
}
}
void main() {
var user1 = User("Alice", Status.Active);
var user2 = User("Bob", Status.Inactive);
user1.display(); // Output: User: Alice, Status: Active
user2.display(); // Output: User: Bob, Status: Inactive
}
class Event {
String name;
Event(this.name);
void trigger() {
print("$name event triggered!");
}
}
void main() {
var event1 = Event("Login");
var event2 = Event("Logout");
event1.trigger(); // Output: Login event triggered!
event2.trigger(); // Output: Logout event triggered!
}