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() {
[Link] = "Unknown Title";
[Link] = "Unknown Author";
[Link] = 0.0;
}
// Constructor with title and author only
public Book(String title, String author) {
[Link] = title;
[Link] = author;
[Link] = 0.0; // Default price
}
// Constructor with all parameters
public Book(String title, String author, double price) {
[Link] = title;
[Link] = author;
[Link] = price;
}
// Method to display book details
public void displayDetails() {
[Link]("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
[Link]();
[Link]();
[Link]();
}
}
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() {
[Link] = 1.0;
[Link] = 1.0;
}
// Constructor that sets only the length, default width
public Rectangle(double length) {
[Link] = length;
[Link] = 1.0; // Default width
}
// Constructor that sets both length and width
public Rectangle(double length, double width) {
[Link] = length;
[Link] = 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
[Link]("Rectangle 1 Area: " + [Link]());
[Link]("Rectangle 2 Area: " + [Link]());
[Link]("Rectangle 3 Area: " + [Link]());
}
}
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() {
[Link] = "000000";
[Link] = "Unknown";
[Link] = 0.0;
}
// Constructor with accountNumber and accountHolderName
public BankAccount(String accountNumber, String accountHolderName) {
[Link] = accountNumber;
[Link] = accountHolderName;
[Link] = 0.0; // Default balance
}
// Constructor with all attributes
public BankAccount(String accountNumber, String accountHolderName, double
balance) {
[Link] = accountNumber;
[Link] = accountHolderName;
[Link] = balance;
}
// Method to display account details
public void displayDetails() {
[Link]("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
[Link]();
[Link]();
[Link]();
}
}
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) {
[Link] = brand;
[Link] = speed;
}
// Method to display processor details
public void displayProcessorDetails() {
[Link]("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) {
[Link] = brand;
[Link] = model;
[Link] = processor;
}
// Method to display computer details
public void displayComputerDetails() {
[Link]("Computer Brand: " + brand + ", Model: " + model);
[Link](); // 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
[Link]();
}
}
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) {
[Link] = resolution;
[Link] = aperture;
}
// Method to display camera details
public void displayCameraDetails() {
[Link]("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) {
[Link] = brand;
[Link] = model;
[Link] = camera;
}
// Method to display smartphone details
public void displaySmartphoneDetails() {
[Link]("Smartphone Brand: " + brand + ", Model: " +
model);
[Link](); // 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
[Link]();
}
}
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 [Link];
import [Link];
// 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) {
[Link] = roomType;
[Link] = area;
}
// Method to display room details
public void displayRoomDetails() {
[Link](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) {
[Link] = houseName;
[Link] = new ArrayList<>(); // Initialize an empty list of rooms
}
// Method to add a room to the house
public void addRoom(Room room) {
[Link](room);
}
// Method to display house details
public void displayHouseDetails() {
[Link]("House Name: " + houseName);
for (Room room : rooms) {
[Link](); // 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
[Link](new Room("Bedroom", 20.0));
[Link](new Room("Kitchen", 15.0));
[Link](new Room("Living Room", 25.0));
// Display details of the house and its rooms
[Link]();
}
}
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 [Link];
import [Link];
// Player class
class Player {
String name;
String position;
// Constructor to initialize Player
public Player(String name, String position) {
[Link] = name;
[Link] = position;
}
// Method to display player details
public void displayPlayerDetails() {
[Link]("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) {
[Link] = teamName;
[Link] = new ArrayList<>(); // Initialize an empty list of
players
}
// Method to add a player to the team
public void addPlayer(Player player) {
[Link](player);
}
// Method to display team details
public void displayTeamDetails() {
[Link]("Team Name: " + teamName);
for (Player player : players) {
[Link](); // 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
[Link](new Player("John", "Forward"));
[Link](new Player("Alice", "Goalkeeper"));
// Display details of the team and its players
[Link]();
}
}
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 [Link];
import [Link];
// Citizen class
class Citizen {
String name;
int age;
// Constructor to initialize Citizen
public Citizen(String name, int age) {
[Link] = name;
[Link] = age;
}
// Method to display citizen details
public void displayCitizenDetails() {
[Link]("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) {
[Link] = cityName;
[Link] = new ArrayList<>(); // Initialize an empty list of
citizens
}
// Method to add a citizen to the city
public void addCitizen(Citizen citizen) {
[Link](citizen);
}
// Method to display city details
public void displayCityDetails() {
[Link]("City Name: " + cityName);
for (Citizen citizen : citizens) {
[Link](); // 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
[Link](new Citizen("John", 30));
[Link](new Citizen("Alice", 25));
// Display details of the city and its citizens
[Link]();
}
}
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 [Link];
import [Link];
// Employee class
class Employee {
String name;
String ID;
double salary;
// Constructor to initialize Employee
public Employee(String name, String ID, double salary) {
[Link] = name;
[Link] = ID;
[Link] = salary;
}
// Method to display employee details
public void displayEmployeeDetails() {
[Link]("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) {
[Link] = departmentName;
[Link] = new ArrayList<>(); // Initialize an empty list of
employees
}
// Method to add an employee to the department
public void addEmployee(Employee employee) {
[Link](employee);
}
// Method to display department details
public void displayDepartmentDetails() {
[Link]("Department Name: " + departmentName);
for (Employee employee : employees) {
[Link](); // 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
[Link](new Employee("John Doe", "E001", 50000));
[Link](new Employee("Jane Smith", "E002", 55000));
// Display details of the department and its employees
[Link]();
}
}
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) {
[Link] = make;
[Link] = year;
}
// Method to display vehicle details
public void displayDetails() {
[Link]("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
[Link] = numberOfDoors;
}
// Method to display car details
public void displayDetails() {
[Link](); // Call Vehicle's display method
[Link]("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
[Link] = type;
}
// Method to display bike details
public void displayDetails() {
[Link](); // Call Vehicle's display method
[Link]("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
[Link]("Car Details:");
[Link]();
[Link]("\nBike Details:");
[Link]();
}
}
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) {
[Link] = name;
[Link] = employeeID;
}
// Method to display employee details
public void displayDetails() {
[Link]("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
[Link] = department;
}
// Method to display manager details
public void displayDetails() {
[Link](); // Call Employee's display method
[Link]("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
[Link] = programmingLanguage;
}
// Method to display developer details
public void displayDetails() {
[Link](); // Call Employee's display method
[Link]("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
[Link]("Manager Details:");
[Link]();
[Link]("\nDeveloper Details:");
[Link]();
}
}
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) {
[Link] = brand;
[Link] = power;
}
// Method to display appliance details
public void displayDetails() {
[Link]("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
[Link] = loadCapacity;
}
// Method to display washing machine details
public void displayDetails() {
[Link](); // Call Appliance's display method
[Link]("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
[Link] = volume;
}
// Method to display refrigerator details
public void displayDetails() {
[Link](); // Call Appliance's display method
[Link]("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
[Link]("Washing Machine Details:");
[Link]();
[Link]("\nRefrigerator Details:");
[Link]();
}
}
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() {
[Link]("Animal makes a sound");
}
}
// Derived class: Dog
class Dog extends Animal {
@Override
public void makeSound() {
[Link]("Dog barks");
}
}
// Derived class: Cat
class Cat extends Animal {
@Override
public void makeSound() {
[Link]("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
[Link](); // Outputs: Dog barks
[Link](); // 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) {
[Link] = radius;
}
@Override
public double area() {
return [Link] * 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) {
[Link] = length;
[Link] = 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
[Link]("Area of Circle: " + [Link]()); // Outputs
area of circle
[Link]("Area of Rectangle: " + [Link]()); //
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() {
[Link]("Processing payment...");
}
}
// Derived class: CreditCardPayment
class CreditCardPayment extends Payment {
@Override
public void processPayment() {
[Link]("Processing credit card payment...");
}
}
// Derived class: CashPayment
class CashPayment extends Payment {
@Override
public void processPayment() {
[Link]("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
[Link](); // Outputs: Processing credit
card payment...
[Link](); // Outputs: Processing cash payment...
}
}