OOP Practice Questions with Solutions in Dart
- Create a class
Person
with properties forname
andage
. Write a method to display the person's details. - Implement a class hierarchy for
Shape
,Circle
, andRectangle
. Include methods to calculate the area for each shape. - Define an abstract class
Animal
with an abstract methodmakeSound()
. Implement theDog
andCat
classes that extendAnimal
. - Create an interface
Playable
with a methodplay()
. Implement this interface in classesGuitar
andPiano
. - Write a program that demonstrates method overriding using a base class
Vehicle
and derived classesCar
andTruck
. - Implement a mixin
Flyable
with a methodfly()
. Create classesBird
andAirplane
that use this mixin. - Create a class
BankAccount
with methods to deposit and withdraw money. Ensure the balance cannot go below zero. - Write a program to demonstrate encapsulation using a class
Student
with private properties forname
andgrade
. - Create a
Book
class that includes properties fortitle
andauthor
and a method to display book information. - Implement a simple CRUD application using classes to represent
User
,Post
, andComment
. - Define a class
Team
with a method to add players. Implement this method to ensure a maximum of 11 players. - Create a class
Calculator
that can perform addition, subtraction, multiplication, and division using method overloading. - Write a program that uses an abstract class
Shape
and derived classesSquare
andTriangle
to calculate the area. - Implement a class
Employee
with properties forname
andsalary
. Include a method to give a raise to the salary. - Create a class
Library
that contains a list ofBook
objects. Implement methods to add and remove books. - Write a program that demonstrates polymorphism by creating a list of
Animal
objects that can be eitherDog
orCat
. - Define a mixin
Loggable
that provides a method to log messages. Implement this mixin in a classLogger
. - Create a class hierarchy for
ElectronicDevice
,Laptop
, andSmartphone
. Include methods for turning on and off. - Implement an interface
Transport
with methodsstart()
andstop()
. Create classesBicycle
andBus
that implement this interface. - Write a program to demonstrate composition using a class
House
that hasRoom
objects as part of its structure.
Solutions with Explanations
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 propertiesname
andage
, and a methoddisplay()
to show the details.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, andCircle
andRectangle
implement thearea()
method.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 methodmakeSound()
, implemented byDog
andCat
.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 bothGuitar
andPiano
, which provide their ownplay()
methods.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 defaultstart()
method, which is overridden byCar
andTruck
.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 addsfly()
functionality to theBird
class.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.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.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 fortitle
andauthor
, and a method to display the information.- 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.
- 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.
- 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()
.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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
.
- 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.
- 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.