OOP Practice Questions with Solutions in Dart
 

  1. Create a class Person with properties for name and age. Write a method to display the person's details.
  2. Implement a class hierarchy for Shape, Circle, and Rectangle. Include methods to calculate the area for each shape.
  3. Define an abstract class Animal with an abstract method makeSound(). Implement the Dog and Cat classes that extend Animal.
  4. Create an interface Playable with a method play(). Implement this interface in classes Guitar and Piano.
  5. Write a program that demonstrates method overriding using a base class Vehicle and derived classes Car and Truck.
  6. Implement a mixin Flyable with a method fly(). Create classes Bird and Airplane that use this mixin.
  7. Create a class BankAccount with methods to deposit and withdraw money. Ensure the balance cannot go below zero.
  8. Write a program to demonstrate encapsulation using a class Student with private properties for name and grade.
  9. Create a Book class that includes properties for title and author and a method to display book information.
  10. Implement a simple CRUD application using classes to represent User, Post, and Comment.
  11. Define a class Team with a method to add players. Implement this method to ensure a maximum of 11 players.
  12. Create a class Calculator that can perform addition, subtraction, multiplication, and division using method overloading.
  13. Write a program that uses an abstract class Shape and derived classes Square and Triangle to calculate the area.
  14. Implement a class Employee with properties for name and salary. Include a method to give a raise to the salary.
  15. Create a class Library that contains a list of Book objects. Implement methods to add and remove books.
  16. Write a program that demonstrates polymorphism by creating a list of Animal objects that can be either Dog or Cat.
  17. Define a mixin Loggable that provides a method to log messages. Implement this mixin in a class Logger.
  18. Create a class hierarchy for ElectronicDevice, Laptop, and Smartphone. Include methods for turning on and off.
  19. Implement an interface Transport with methods start() and stop(). Create classes Bicycle and Bus that implement this interface.
  20. Write a program to demonstrate composition using a class House that has Room objects as part of its structure.

Solutions with Explanations

  1. Class Person:

    class Person {
      String name;
      int age;
    
      Person(this.name, this.age);
    
      void display() {
        print('Name: $name, Age: $age');
      }
    }
    
    void main() {
      Person person = Person('Alice', 30);
      person.display(); // Output: Name: Alice, Age: 30 
      }
    

    Explanation: The Person class has properties name and age, and a method display() to show the details.

  2. Class Hierarchy for Shapes:

    abstract class Shape {
      double area();
    }
    
    class Circle extends Shape {
      double radius;
    
      Circle(this.radius);
    
      @override   double area() => 3.14 * radius * radius; // Area calculation }
    
    class Rectangle extends Shape {
      double width, height;
    
      Rectangle(this.width, this.height);
    
      @override   double area() => width * height; // Area calculation }
    
    void main() {
      Shape circle = Circle(5);
      Shape rectangle = Rectangle(4, 6);
      print('Circle Area: ${circle.area()}'); // Output: Circle Area: 78.5   
      print('Rectangle Area: ${rectangle.area()}'); // Output: Rectangle Area: 24.0 
      }
    

    Explanation: The Shape class is abstract, and Circle and Rectangle implement the area() method.

  3. Abstract Class Animal:

    abstract class Animal {
      void makeSound();
    }
    
    class Dog extends Animal {
      @override   void makeSound() {
        print('Bark');
      }
    }
    
    class Cat extends Animal {
      @override   void makeSound() {
        print('Meow');
      }
    }
    
    void main() {
      Animal dog = Dog();
      Animal cat = Cat();
      dog.makeSound(); // Output: Bark   
      cat.makeSound(); // Output: Meow 
      }
    

    Explanation: Animal is an abstract class with an abstract method makeSound(), implemented by Dog and Cat.

  4. Interface Playable:

    abstract class Playable {
      void play();
    }
    
    class Guitar implements Playable {
      @override   void play() {
        print('Playing Guitar');
      }
    }
    
    class Piano implements Playable {
      @override   void play() {
        print('Playing Piano');
      }
    }
    
    void main() {
      Playable guitar = Guitar();
      Playable piano = Piano();
      guitar.play(); // Output: Playing Guitar   
      piano.play(); // Output: Playing Piano 
      }
    

    Explanation: The Playable interface is implemented by both Guitar and Piano, which provide their own play() methods.

  5. Method Overriding in Vehicle:

    class Vehicle {
      void start() {
        print('Vehicle starting');
      }
    }
    
    class Car extends Vehicle {
      @override   void start() {
        print('Car starting');
      }
    }
    
    class Truck extends Vehicle {
      @override   void start() {
        print('Truck starting');
      }
    }
    
    void main() {
      Vehicle myCar = Car();
      Vehicle myTruck = Truck();
      myCar.start(); // Output: Car starting   
      myTruck.start(); // Output: Truck starting 
      }
    

    Explanation: The Vehicle class provides a default start() method, which is overridden by Car and Truck.

  6. Mixin Flyable:

    mixin Flyable {
      void fly() {
        print('Flying...');
      }
    }
    
    class Bird with Flyable {
      void chirp() {
        print('Chirping...');
      }
    }
    
    void main() {
      Bird bird = Bird();
      bird.fly(); // Output: Flying...   
      bird.chirp(); // Output: Chirping... 
      }
    

    Explanation: The Flyable mixin adds fly() functionality to the Bird class.

  7. Class BankAccount:

    class BankAccount {
      double _balance = 0;
    
      void deposit(double amount) {
        if (amount > 0) {
          _balance += amount;
          print('Deposited: \$${amount}');
        }
      }
    
      void withdraw(double amount) {
        if (amount > 0 && amount <= _balance) {
          _balance -= amount;
          print('Withdrawn: \$${amount}');
        } else {
          print('Insufficient funds.');
        }
      }
    
      double get balance => _balance;
    }
    
    void main() {
      BankAccount account = BankAccount();
      account.deposit(100);
      account.withdraw(50);
      print('Balance: \$${account.balance}'); // Output: Balance: $50.0 
      }
    

    Explanation: The BankAccount class manages deposits and withdrawals while keeping the balance private.

  8. Encapsulation with Student:

    class Student {
      String _name;
      int _grade;
    
      Student(this._name, this._grade);
    
      String get name => _name;
      int get grade => _grade;
    
      void display() {
        print('Name: $_name, Grade: $_grade');
      }
    }
    
    void main() {
      Student student = Student('John', 90);
      student.display(); // Output: Name: John, Grade: 90 
      }
    

    Explanation: The Student class uses private properties _name and _grade with public getters.

  9. Class Book:

    class Book {
      String title;
      String author;
    
      Book(this.title, this.author);
    
      void displayInfo() {
        print('Title: $title, Author: $author');
      }
    }
    
    void main() {
      Book book = Book('1984', 'George Orwell');
      book.displayInfo(); // Output: Title: 1984, Author: George Orwell
       }
    

    Explanation: The Book class has properties for title and author, and a method to display the information.

  10. Simple CRUD Application:
class User {
  String name;

  User(this.name);
}

class Post {
  String title;

  Post(this.title);
}

class Comment {
  String content;

  Comment(this.content);
}

void main() {
  User user = User('Alice');
  Post post = Post('Hello World');
  Comment comment = Comment('Great post!');

  print('User: ${user.name}, Post: ${post.title}, Comment: ${comment.content}');
}

Explanation: This simple implementation creates User, Post, and Comment classes to demonstrate basic CRUD operations.

  1. Class Team:
class Team {
  List<String> players = [];

  void addPlayer(String player) {
    if (players.length < 11) {
      players.add(player);
      print('$player added to the team.');
    } else {
      print('Team is full. Cannot add more players.');
    }
  }
}

void main() {
  Team team = Team();
  team.addPlayer('Player 1');
  team.addPlayer('Player 2');
  // Add more players...   for (var i = 3; i <= 12; i++) {
    team.addPlayer('Player $i');
  }
}

Explanation: The Team class allows adding players while enforcing a maximum of 11 players.

  1. Class Calculator:

 

class Calculator {
  int add(int a, int b) => a + b;
  double add(double a, double b) => a + b; // Method overloading 
  }

void main() {
  Calculator calc = Calculator();
  print(calc.add(5, 10)); // Output: 15   
  print(calc.add(5.5, 10.5)); // Output: 16.0 
  }

Explanation: The Calculator class demonstrates method overloading by providing different implementations for add().

  1. Abstract Class Shape:
abstract class Shape {
  double area();
}

class Square extends Shape {
  double side;

  Square(this.side);

  @override   double area() => side * side; // Area calculation 
  }

class Triangle extends Shape {
  double base, height;

  Triangle(this.base, this.height);

  @override   double area() => 0.5 * base * height; // Area calculation 
  }

void main() {
  Shape square = Square(4);
  Shape triangle = Triangle(4, 5);
  print('Square Area: ${square.area()}'); // Output: Square Area: 16.0   
  print('Triangle Area: ${triangle.area()}'); // Output: Triangle Area: 10.0 
  }

Explanation: The abstract class Shape enforces the implementation of area() in derived classes.

  1. Class Employee:
class Employee {
  String name;
  double salary;

  Employee(this.name, this.salary);

  void giveRaise(double percentage) {
    salary += salary * (percentage / 100);
    print('$name\'s new salary: \$${salary}');
  }
}

void main() {
  Employee emp = Employee('Alice', 50000);
  emp.giveRaise(10); // Output: Alice's new salary: $55000.0 
  }

Explanation: The Employee class has a method to give a raise based on a percentage increase.

  1. Class Library:

 

class Book {
  String title;

  Book(this.title);
}

class Library {
  List<Book> books = [];

  void addBook(Book book) {
    books.add(book);
    print('Book added: ${book.title}');
  }

  void removeBook(Book book) {
    books.remove(book);
    print('Book removed: ${book.title}');
  }
}

void main() {
  Library library = Library();
  Book book1 = Book('1984');
  library.addBook(book1);
  library.removeBook(book1);
}

Explanation: The Library class manages a list of Book objects, allowing adding and removing books.

  1. Demonstrating Polymorphism:

 

class Animal {
  void makeSound() {
    print('Animal makes a sound');
  }
}

class Dog extends Animal {
  @override   void makeSound() {
    print('Bark');
  }
}

class Cat extends Animal {
  @override   void makeSound() {
    print('Meow');
  }
}

void main() {
  List<Animal> animals = [Dog(), Cat()];
  for (var animal in animals) {
    animal.makeSound(); // Output: Bark, Meow  
     }
}

Explanation: This demonstrates polymorphism by calling the makeSound() method on a list of Animal objects.

  1. Mixin Loggable:
mixin Loggable {
  void log(String message) {
    print('Log: $message');
  }
}

class Logger with Loggable {
  void performAction() {
    log('Action performed');
  }
}

void main() {
  Logger logger = Logger();
  logger.performAction(); // Output: Log: Action performed 
  }

Explanation: The Loggable mixin provides logging functionality to the Logger class.

  1. Class Hierarchy for Devices:
class ElectronicDevice {
  void turnOn() {
    print('Device is turned on');
  }

  void turnOff() {
    print('Device is turned off');
  }
}

class Laptop extends ElectronicDevice {}

class Smartphone extends ElectronicDevice {}

void main() {
  Laptop myLaptop = Laptop();
  Smartphone myPhone = Smartphone();
  myLaptop.turnOn(); // Output: Device is turned on   
  myPhone.turnOff(); // Output: Device is turned off }
  

Explanation: The ElectronicDevice class provides common functionality for both Laptop and Smartphone.

  1. Interface Transport:

 

abstract class Transport {
  void start();
  void stop();
}

class Bicycle implements Transport {
  @override   void start() {
    print('Bicycle started');
  }

  @override   void stop() {
    print('Bicycle stopped');
  }
}

class Bus implements Transport {
  @override   void start() {
    print('Bus started');
  }

  @override   void stop() {
    print('Bus stopped');
  }
}

void main() {
  Transport bike = Bicycle();
  Transport bus = Bus();
  bike.start(); // Output: Bicycle started   
  bus.start(); // Output: Bus started 
  }

Explanation: The Transport interface is implemented by both Bicycle and Bus, which provide their own start() and stop() methods.

  1. Composition with House:
class Room {
  String name;

  Room(this.name);
}

class House {
  List<Room> rooms = [];

  void addRoom(Room room) {
    rooms.add(room);
    print('Room added: ${room.name}');
  }
}

void main() {
  House house = House();
  Room livingRoom = Room('Living Room');
  house.addRoom(livingRoom); // Output: Room added: Living Room 
  }

Explanation: The House class uses composition to include Room objects as part of its structure, demonstrating how one class can contain instances of another.