1.
Constructor Overloading: Book Class
Question: Create a Book class with attributes title, author, and price. Implement the
following overloaded constructors:
One that takes no parameters and initializes default values.
One that takes only the title and author.
One that takes all three attributes: title, author, and price.
Solution:
class Book {
String title;
String author;
double price;
// Constructor with no parameters, sets default values
public Book() {
this.title = "Unknown Title";
this.author = "Unknown Author";
this.price = 0.0;
}
// Constructor with title and author only
public Book(String title, String author) {
this.title = title;
this.author = author;
this.price = 0.0; // Default price
}
// Constructor with all parameters
public Book(String title, String author, double price) {
this.title = title;
this.author = author;
this.price = price;
}
// Method to display book details
public void displayDetails() {
System.out.println("Title: " + title + ", Author: " + author + ",
Price: $" + price);
}
public static void main(String[] args) {
// Create objects using different constructors
Book book1 = new Book();
Book book2 = new Book("The Alchemist", "Paulo Coelho");
Book book3 = new Book("1984", "George Orwell", 15.99);
// Display the details of each book
book1.displayDetails();
book2.displayDetails();
book3.displayDetails();
}
}
2. Constructor Overloading: Rectangle Class
Question: Write a Rectangle class that has attributes length and width. Implement multiple
constructors:
A constructor that sets both dimensions to a default value.
A constructor that sets only the length.
A constructor that sets both length and width.
Solution:
class Rectangle {
double length;
double width;
// Constructor with default values for length and width
public Rectangle() {
this.length = 1.0;
this.width = 1.0;
}
// Constructor that sets only the length, default width
public Rectangle(double length) {
this.length = length;
this.width = 1.0; // Default width
}
// Constructor that sets both length and width
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
// Method to calculate the area of the rectangle
public double calculateArea() {
return length * width;
}
public static void main(String[] args) {
// Create objects using different constructors
Rectangle rect1 = new Rectangle();
Rectangle rect2 = new Rectangle(5.0);
Rectangle rect3 = new Rectangle(4.0, 6.0);
// Calculate and display the area of each rectangle
System.out.println("Rectangle 1 Area: " + rect1.calculateArea());
System.out.println("Rectangle 2 Area: " + rect2.calculateArea());
System.out.println("Rectangle 3 Area: " + rect3.calculateArea());
}
}
3. Constructor Overloading: BankAccount Class
Question: Create a BankAccount class with attributes accountNumber, accountHolderName,
and balance. Implement overloaded constructors:
One that takes no arguments.
One that takes accountNumber and accountHolderName.
One that takes all attributes (accountNumber, accountHolderName, and balance).
Solution:
class BankAccount {
String accountNumber;
String accountHolderName;
double balance;
// Constructor with no arguments, initializes default values
public BankAccount() {
this.accountNumber = "000000";
this.accountHolderName = "Unknown";
this.balance = 0.0;
}
// Constructor with accountNumber and accountHolderName
public BankAccount(String accountNumber, String accountHolderName) {
this.accountNumber = accountNumber;
this.accountHolderName = accountHolderName;
this.balance = 0.0; // Default balance
}
// Constructor with all attributes
public BankAccount(String accountNumber, String accountHolderName, double
balance) {
this.accountNumber = accountNumber;
this.accountHolderName = accountHolderName;
this.balance = balance;
}
// Method to display account details
public void displayDetails() {
System.out.println("Account Number: " + accountNumber +
", Account Holder: " + accountHolderName +
", Balance: $" + balance);
}
public static void main(String[] args) {
// Create objects using different constructors
BankAccount account1 = new BankAccount();
BankAccount account2 = new BankAccount("123456", "John Doe");
BankAccount account3 = new BankAccount("789012", "Jane Smith",
500.0);
// Display account details
account1.displayDetails();
account2.displayDetails();
account3.displayDetails();
}
}
4. Composition: Computer and Processor Classes
Question: Create a Computer class that has a Processor class as a member. The Processor
class has attributes brand and speed. The Computer class has attributes brand, model, and a
Processor object.
Solution:
// Processor class (a part of Computer)
class Processor {
String brand;
double speed; // in GHz
// Constructor to initialize Processor
public Processor(String brand, double speed) {
this.brand = brand;
this.speed = speed;
}
// Method to display processor details
public void displayProcessorDetails() {
System.out.println("Processor Brand: " + brand + ", Speed: " + speed
+ " GHz");
}
}
// Computer class (contains a Processor)
class Computer {
String brand;
String model;
Processor processor; // Composition: Processor is part of Computer
// Constructor to initialize Computer with Processor
public Computer(String brand, String model, Processor processor) {
this.brand = brand;
this.model = model;
this.processor = processor;
}
// Method to display computer details
public void displayComputerDetails() {
System.out.println("Computer Brand: " + brand + ", Model: " + model);
processor.displayProcessorDetails(); // Display processor info
}
public static void main(String[] args) {
// Create a Processor object
Processor processor = new Processor("Intel", 3.5);
// Create a Computer object with a Processor
Computer computer = new Computer("Dell", "Inspiron", processor);
// Display details of the computer and its processor
computer.displayComputerDetails();
}
}
5. Composition: Smartphone and Camera Classes
Question: Write a Smartphone class that has a Camera class as a member. The Camera class has
attributes resolution and aperture. The Smartphone class has attributes brand, model, and a
Camera object.
Solution:
// Camera class (a part of Smartphone)
class Camera {
String resolution;
double aperture;
// Constructor to initialize Camera
public Camera(String resolution, double aperture) {
this.resolution = resolution;
this.aperture = aperture;
}
// Method to display camera details
public void displayCameraDetails() {
System.out.println("Camera Resolution: " + resolution + ", Aperture:
" + aperture);
}
}
// Smartphone class (contains a Camera)
class Smartphone {
String brand;
String model;
Camera camera; // Composition: Camera is part of Smartphone
// Constructor to initialize Smartphone with Camera
public Smartphone(String brand, String model, Camera camera) {
this.brand = brand;
this.model = model;
this.camera = camera;
}
// Method to display smartphone details
public void displaySmartphoneDetails() {
System.out.println("Smartphone Brand: " + brand + ", Model: " +
model);
camera.displayCameraDetails(); // Display camera info
}
public static void main(String[] args) {
// Create a Camera object
Camera camera = new Camera("12MP", 1.8);
// Create a Smartphone object with a Camera
Smartphone smartphone = new Smartphone("Samsung", "Galaxy S20",
camera);
// Display details of the smartphone and its camera
smartphone.displaySmartphoneDetails();
}
}
6. Composition: House and Room Classes
Question: Create a House class that contains a Room class. The Room class has attributes
roomType and area. The House class has a HouseName and a list of Room objects.
Solution:
import java.util.ArrayList;
import java.util.List;
// Room class (a part of House)
class Room {
String roomType;
double area; // in square meters
// Constructor to initialize Room
public Room(String roomType, double area) {
this.roomType = roomType;
this.area = area;
}
// Method to display room details
public void displayRoomDetails() {
System.out.println(roomType + " - Area: " + area + " sq.m");
}
}
// House class (contains multiple Room objects)
class House {
String houseName;
List<Room> rooms; // Composition: House contains a list of Room objects
// Constructor to initialize House
public House(String houseName) {
this.houseName = houseName;
this.rooms = new ArrayList<>(); // Initialize an empty list of rooms
}
// Method to add a room to the house
public void addRoom(Room room) {
rooms.add(room);
}
// Method to display house details
public void displayHouseDetails() {
System.out.println("House Name: " + houseName);
for (Room room : rooms) {
room.displayRoomDetails(); // Display details of each room
}
}
public static void main(String[] args) {
// Create a House object
House house = new House("Dream Villa");
// Create Room objects and add them to the house
house.addRoom(new Room("Bedroom", 20.0));
house.addRoom(new Room("Kitchen", 15.0));
house.addRoom(new Room("Living Room", 25.0));
// Display details of the house and its rooms
house.displayHouseDetails();
}
}
7. Aggregation: Team and Player Classes
Question: Write a Team class and a Player class. The Player class has attributes name and
position. The Team class has a teamName and a list of Player objects.
Solution:
import java.util.ArrayList;
import java.util.List;
// Player class
class Player {
String name;
String position;
// Constructor to initialize Player
public Player(String name, String position) {
this.name = name;
this.position = position;
}
// Method to display player details
public void displayPlayerDetails() {
System.out.println("Player: " + name + ", Position: " + position);
}
}
// Team class (aggregates Player objects)
class Team {
String teamName;
List<Player> players; // Aggregation: Team contains a list of Player
objects
// Constructor to initialize Team
public Team(String teamName) {
this.teamName = teamName;
this.players = new ArrayList<>(); // Initialize an empty list of
players
}
// Method to add a player to the team
public void addPlayer(Player player) {
players.add(player);
}
// Method to display team details
public void displayTeamDetails() {
System.out.println("Team Name: " + teamName);
for (Player player : players) {
player.displayPlayerDetails(); // Display each player's details
}
}
public static void main(String[] args) {
// Create a Team object
Team team = new Team("Dream Team");
// Create Player objects and add them to the team
team.addPlayer(new Player("John", "Forward"));
team.addPlayer(new Player("Alice", "Goalkeeper"));
// Display details of the team and its players
team.displayTeamDetails();
}
}
8. Aggregation: City and Citizen Classes
Question: Create a City class and a Citizen class. The Citizen class has attributes name and
age. The City class has an attribute cityName and a list of Citizen objects.
Solution:
import java.util.ArrayList;
import java.util.List;
// Citizen class
class Citizen {
String name;
int age;
// Constructor to initialize Citizen
public Citizen(String name, int age) {
this.name = name;
this.age = age;
}
// Method to display citizen details
public void displayCitizenDetails() {
System.out.println("Citizen: " + name + ", Age: " + age);
}
}
// City class (aggregates Citizen objects)
class City {
String cityName;
List<Citizen> citizens; // Aggregation: City contains a list of Citizen
objects
// Constructor to initialize City
public City(String cityName) {
this.cityName = cityName;
this.citizens = new ArrayList<>(); // Initialize an empty list of
citizens
}
// Method to add a citizen to the city
public void addCitizen(Citizen citizen) {
citizens.add(citizen);
}
// Method to display city details
public void displayCityDetails() {
System.out.println("City Name: " + cityName);
for (Citizen citizen : citizens) {
citizen.displayCitizenDetails(); // Display each citizen's
details
}
}
public static void main(String[] args) {
// Create a City object
City city = new City("Metropolis");
// Create Citizen objects and add them to the city
city.addCitizen(new Citizen("John", 30));
city.addCitizen(new Citizen("Alice", 25));
// Display details of the city and its citizens
city.displayCityDetails();
}
}
9. Aggregation: Department and Employee Classes
Question: Design a Department class and an Employee class. The Employee class has attributes
name, ID, and salary. The Department class has a departmentName and a list of Employee
objects.
Solution:
import java.util.ArrayList;
import java.util.List;
// Employee class
class Employee {
String name;
String ID;
double salary;
// Constructor to initialize Employee
public Employee(String name, String ID, double salary) {
this.name = name;
this.ID = ID;
this.salary = salary;
}
// Method to display employee details
public void displayEmployeeDetails() {
System.out.println("Employee Name: " + name + ", ID: " + ID + ",
Salary: $" + salary);
}
}
// Department class (aggregates Employee objects)
class Department {
String departmentName;
List<Employee> employees; // Aggregation: Department contains a list of
Employee objects
// Constructor to initialize Department
public Department(String departmentName) {
this.departmentName = departmentName;
this.employees = new ArrayList<>(); // Initialize an empty list of
employees
}
// Method to add an employee to the department
public void addEmployee(Employee employee) {
employees.add(employee);
}
// Method to display department details
public void displayDepartmentDetails() {
System.out.println("Department Name: " + departmentName);
for (Employee employee : employees) {
employee.displayEmployeeDetails(); // Display each employee's
details
}
}
public static void main(String[] args) {
// Create a Department object
Department department = new Department("Sales");
// Create Employee objects and add them to the department
department.addEmployee(new Employee("John Doe", "E001", 50000));
department.addEmployee(new Employee("Jane Smith", "E002", 55000));
// Display details of the department and its employees
department.displayDepartmentDetails();
}
}
10. Inheritance: Vehicle, Car, and Bike Classes
Question: Create a base class Vehicle with attributes make and year. Derive a class Car that
adds an attribute numberOfDoors. Derive a class Bike that adds an attribute type (e.g., sports,
cruiser).
Solution:
// Base class: Vehicle
class Vehicle {
String make;
int year;
// Constructor to initialize Vehicle
public Vehicle(String make, int year) {
this.make = make;
this.year = year;
}
// Method to display vehicle details
public void displayDetails() {
System.out.println("Make: " + make + ", Year: " + year);
}
}
// Derived class: Car
class Car extends Vehicle {
int numberOfDoors;
// Constructor to initialize Car
public Car(String make, int year, int numberOfDoors) {
super(make, year); // Call Vehicle constructor
this.numberOfDoors = numberOfDoors;
}
// Method to display car details
public void displayDetails() {
super.displayDetails(); // Call Vehicle's display method
System.out.println("Number of Doors: " + numberOfDoors);
}
}
// Derived class: Bike
class Bike extends Vehicle {
String type;
// Constructor to initialize Bike
public Bike(String make, int year, String type) {
super(make, year); // Call Vehicle constructor
this.type = type;
}
// Method to display bike details
public void displayDetails() {
super.displayDetails(); // Call Vehicle's display method
System.out.println("Type: " + type);
}
public static void main(String[] args) {
// Create objects of Car and Bike
Car car = new Car("Toyota", 2020, 4);
Bike bike = new Bike("Yamaha", 2022, "Sports");
// Display details of the car and bike
System.out.println("Car Details:");
car.displayDetails();
System.out.println("\nBike Details:");
bike.displayDetails();
}
}
11. Inheritance: Employee, Manager, and Developer Classes
Question: Create a base class Employee with attributes name and employeeID. Derive a class
Manager that adds an attribute department. Derive a class Developer that adds an attribute
programmingLanguage.
Solution:
// Base class: Employee
class Employee {
String name;
String employeeID;
// Constructor to initialize Employee
public Employee(String name, String employeeID) {
this.name = name;
this.employeeID = employeeID;
}
// Method to display employee details
public void displayDetails() {
System.out.println("Employee Name: " + name + ", Employee ID: " +
employeeID);
}
}
// Derived class: Manager
class Manager extends Employee {
String department;
// Constructor to initialize Manager
public Manager(String name, String employeeID, String department) {
super(name, employeeID); // Call Employee constructor
this.department = department;
}
// Method to display manager details
public void displayDetails() {
super.displayDetails(); // Call Employee's display method
System.out.println("Department: " + department);
}
}
// Derived class: Developer
class Developer extends Employee {
String programmingLanguage;
// Constructor to initialize Developer
public Developer(String name, String employeeID, String
programmingLanguage) {
super(name, employeeID); // Call Employee constructor
this.programmingLanguage = programmingLanguage;
}
// Method to display developer details
public void displayDetails() {
super.displayDetails(); // Call Employee's display method
System.out.println("Programming Language: " + programmingLanguage);
}
public static void main(String[] args) {
// Create objects of Manager and Developer
Manager manager = new Manager("Alice", "M001", "Sales");
Developer developer = new Developer("Bob", "D001", "Java");
// Display details of the manager and developer
System.out.println("Manager Details:");
manager.displayDetails();
System.out.println("\nDeveloper Details:");
developer.displayDetails();
}
}
12. Inheritance: Appliance, WashingMachine, and Refrigerator Classes
Question: Create a base class Appliance with attributes brand and power. Derive a class
WashingMachine that adds an attribute loadCapacity. Derive a class Refrigerator that adds
an attribute volume.
Solution:
// Base class: Appliance
class Appliance {
String brand;
double power; // in watts
// Constructor to initialize Appliance
public Appliance(String brand, double power) {
this.brand = brand;
this.power = power;
}
// Method to display appliance details
public void displayDetails() {
System.out.println("Brand: " + brand + ", Power: " + power + "W");
}
}
// Derived class: WashingMachine
class WashingMachine extends Appliance {
double loadCapacity; // in kg
// Constructor to initialize WashingMachine
public WashingMachine(String brand, double power, double loadCapacity) {
super(brand, power); // Call Appliance constructor
this.loadCapacity = loadCapacity;
}
// Method to display washing machine details
public void displayDetails() {
super.displayDetails(); // Call Appliance's display method
System.out.println("Load Capacity: " + loadCapacity + " kg");
}
}
// Derived class: Refrigerator
class Refrigerator extends Appliance {
double volume; // in liters
// Constructor to initialize Refrigerator
public Refrigerator(String brand, double power, double volume) {
super(brand, power); // Call Appliance constructor
this.volume = volume;
}
// Method to display refrigerator details
public void displayDetails() {
super.displayDetails(); // Call Appliance's display method
System.out.println("Volume: " + volume + " liters");
}
public static void main(String[] args) {
// Create objects of WashingMachine and Refrigerator
WashingMachine washingMachine = new WashingMachine("LG", 2000, 7.5);
Refrigerator refrigerator = new Refrigerator("Samsung", 150, 300);
// Display details of the washing machine and refrigerator
System.out.println("Washing Machine Details:");
washingMachine.displayDetails();
System.out.println("\nRefrigerator Details:");
refrigerator.displayDetails();
}
}
13. Polymorphism: Animal Class and Subclasses
Question: Create a base class Animal with a method makeSound(). Derive classes Dog and Cat,
and override the makeSound() method for each.
Solution:
// Base class: Animal
class Animal {
// Method to be overridden
public void makeSound() {
System.out.println("Animal makes a sound");
}
}
// Derived class: Dog
class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("Dog barks");
}
}
// Derived class: Cat
class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("Cat meows");
}
}
// Main class to demonstrate polymorphism
public class Main {
public static void main(String[] args) {
Animal myDog = new Dog(); // Animal reference, Dog object
Animal myCat = new Cat(); // Animal reference, Cat object
// Call the overridden methods
myDog.makeSound(); // Outputs: Dog barks
myCat.makeSound(); // Outputs: Cat meows
}
}
14. Polymorphism: Shape Class and Subclasses
Question: Create a base class Shape with a method area(). Derive classes Circle and
Rectangle, and override the area() method for each.
Solution:
// Base class: Shape
class Shape {
// Method to be overridden
public double area() {
return 0; // Default implementation
}
}
// Derived class: Circle
class Circle extends Shape {
double radius;
// Constructor to initialize Circle
public Circle(double radius) {
this.radius = radius;
}
@Override
public double area() {
return Math.PI * radius * radius; // Area of circle
}
}
// Derived class: Rectangle
class Rectangle extends Shape {
double length;
double width;
// Constructor to initialize Rectangle
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
@Override
public double area() {
return length * width; // Area of rectangle
}
}
// Main class to demonstrate polymorphism
public class Main {
public static void main(String[] args) {
Shape circle = new Circle(5); // Shape reference, Circle object
Shape rectangle = new Rectangle(4, 6); // Shape reference, Rectangle
object
// Call the overridden methods
System.out.println("Area of Circle: " + circle.area()); // Outputs
area of circle
System.out.println("Area of Rectangle: " + rectangle.area()); //
Outputs area of rectangle
}
}
15. Polymorphism: Payment Class and Subclasses
Question: Create a base class Payment with a method processPayment(). Derive classes
CreditCardPayment and CashPayment, and override the processPayment() method for each.
Solution:
// Base class: Payment
class Payment {
// Method to be overridden
public void processPayment() {
System.out.println("Processing payment...");
}
}
// Derived class: CreditCardPayment
class CreditCardPayment extends Payment {
@Override
public void processPayment() {
System.out.println("Processing credit card payment...");
}
}
// Derived class: CashPayment
class CashPayment extends Payment {
@Override
public void processPayment() {
System.out.println("Processing cash payment...");
}
}
// Main class to demonstrate polymorphism
public class Main {
public static void main(String[] args) {
Payment creditCardPayment = new CreditCardPayment(); // Payment
reference, CreditCardPayment object
Payment cashPayment = new CashPayment(); // Payment reference,
CashPayment object
// Call the overridden methods
creditCardPayment.processPayment(); // Outputs: Processing credit
card payment...
cashPayment.processPayment(); // Outputs: Processing cash payment...
}
}