oop_codes
oop_codes
// Parameterized constructor
this.departmentId = departmentId;
this.departmentName = departmentName;
// Employee.java
// Default constructor
public Employee() {
// Parameterized constructor
this.employeeId = employeeId;
this.employeeName = employeeName;
this.department = department;
if (department != null) {
System.out.println("\nDepartment Information:");
department.displayDepartmentDetails();
} else {
// EmployeeDepartmentApp.java
emp1.setDepartment(itDepartment);
emp2.setDepartment(itDepartment);
emp1.displayEmployeeDetails();
emp2.displayEmployeeDetails();
}
Question 2: University-Professor System (Aggregation)
// Professor.java
// Parameterized constructor
this.professorId = professorId;
this.professorName = professorName;
// University.java
public class University {
this.universityName = universityName;
professors[professorCount] = prof;
professorCount++;
} else {
professors[i].displayProfessorDetails();
} else {
// UniversityProfessorApp.java
harvard.addProfessor(prof1);
harvard.addProfessor(prof2);
harvard.addProfessor(prof3);
// Display university details
harvard.displayUniversityDetails();
Develop a Car-Engine System that demonstrates composition, where a Car contains an Engine that
cannot exist without the Car. The Engine class should represent a car engine with attributes
engineType and horsepower (int). It should include a parameterized constructor to initialize these
attributes and a method displayEngineDetails() to print engine information. The Car class should
model a car that must have an engine. It should include attributes carModel (String) and engine
(Engine). The class should have a constructor that creates a new Engine as part of its initialization,
making the Engine's lifecycle dependent on the Car. It should also include a displayCarDetails()
method to print car information and engine details. In the main method, create two Car objects with
different engine types and display their details.
// Engine.java
// Parameterized constructor
this.engineType = engineType;
this.horsepower = horsepower;
}
}
// Car.java
this.carModel = carModel;
System.out.println("\nEngine Information:");
engine.displayEngineDetails();
// CarEngineApp.java
car1.displayCarDetails();
car2.displayCarDetails();
Develop a Bank-Account System that demonstrates inheritance, where different types of accounts
inherit from a base Account class. The Account class should be the parent class with attributes
accountNumber (String) and balance (double). It should include a constructor to initialize these
attributes, methods deposit(double amount) and withdraw(double amount) to modify the balance,
and a displayAccountDetails() method. The SavingsAccount class should extend Account and add an
attribute interestRate (double). It should override the displayAccountDetails() method to include
interest rate information and add a calculateInterest() method. The CheckingAccount class should
also extend Account and add an attribute overdraftLimit (double). It should override the withdraw()
method to allow withdrawals up to the overdraft limit and override the displayAccountDetails()
method. In the main method, create objects of both account types, perform transactions, and
display their details.
// Account.java
// Constructor
this.accountNumber = accountNumber;
this.balance = initialBalance;
if (amount > 0) {
balance += amount;
} else {
balance -= amount;
} else {
}
// SavingsAccount.java
// Constructor
this.interestRate = interestRate;
return interest;
deposit(interest);
@Override
// CheckingAccount.java
// Constructor
this.overdraftLimit = overdraftLimit;
@Override
balance -= amount;
if (balance < 0) {
} else {
}
}
@Override
// BankAccountApp.java
// Create a SavingsAccount
// Create a CheckingAccount
// Perform transactions
savings.deposit(500.0);
savings.withdraw(200.0);
savings.applyInterest();
savings.displayAccountDetails();
checking.displayAccountDetails();
Develop an Order System where an OrderProcessor class processes an Order object temporarily
without storing a reference to it. The Order class should represent a customer order with attributes
orderId (String), customerName (String), and totalAmount (double). It should include a
parameterized constructor to initialize these attributes and a method displayOrderDetails() to print
order information. The OrderProcessor class should model a processor that handles orders. It should
not store any reference to the Order object. Instead, it should contain methods processOrder(Order
order) that validates the order and calculates taxes, and generateInvoice(Order order) that creates
an invoice for the order. These methods should demonstrate a dependency relationship by using the
Order only during method execution. In the main method, create an Order object and use an
OrderProcessor to process it and generate an invoice.
// Parameterized constructor
this.orderId = orderId;
this.customerName = customerName;
this.totalAmount = totalAmount;
}
// Getters
return orderId;
return customerName;
return totalAmount;
// OrderProcessor.java
return;
}
// Helper method to calculate tax
// OrderSystemApp.java
// Create OrderProcessor
order.displayOrderDetails();
processor.processOrder(order);
// Generate invoice
processor.generateInvoice(order);
}
Summary of Object-Oriented Relationships in the Questions
o Shows association where Employee and Department are connected but exist
independently
I'll create 5 more questions that demonstrate the different relationships in object-oriented
programming, following the same format as before.
Develop a Hotel-Guest System where a Guest is associated with a Hotel during their stay, but they
exist independently. The Hotel class should have attributes hotelId and hotelName, both of type
String. It should include a parameterized constructor to initialize these attributes and a method
displayHotelDetails() to print hotel information. The Guest class should model a guest with attributes
guestId, guestName, and currentHotel (of type Hotel). It should include a default constructor, a
parameterized constructor for guest details, a method checkIn(Hotel hotel) to associate with a hotel,
checkOut() to end the association, and displayGuestDetails() to print guest information and current
hotel (if any). In the main method, create a Hotel object and two Guest objects, check them in to the
hotel, display details, then check one guest out and display the updated information.
// Parameterized constructor
this.hotelId = hotelId;
this.hotelName = hotelName;
// Guest.java
public class Guest {
// Default constructor
public Guest() {
// Parameterized constructor
this.guestId = guestId;
this.guestName = guestName;
this.currentHotel = hotel;
if (currentHotel != null) {
this.currentHotel = null;
} else {
System.out.println(guestName + " is not currently staying at any hotel");
if (currentHotel != null) {
currentHotel.displayHotelDetails();
} else {
// HotelGuestApp.java
guest1.checkIn(grandHotel);
guest2.checkIn(grandHotel);
guest1.displayGuestDetails();
guest2.displayGuestDetails();
guest1.checkOut();
guest1.displayGuestDetails();
guest2.displayGuestDetails();
}
Question 7: Store-Product System (Aggregation)
Develop a Store-Product System where a Store contains multiple Products, but Products can exist
independently and can be transferred between Stores. The Product class should have attributes
productId, productName, and price (double). It should include a parameterized constructor to
initialize these attributes and a method displayProductDetails() to print product information. The
Store class should model a store that can contain up to ten products. It should include attributes
storeId, storeName, and an array of Product objects (size 10), along with a count of current
products. It should provide methods addProduct(Product product) to add a product to the array,
removeProduct(String productId) to remove a product from the store, and displayStoreDetails() to
print store information and all products. In the main method, create two Store objects and three
Product objects, add products to the first store, display details, then transfer a product to the second
store and display updated information for both stores.
// Product.java
// Parameterized constructor
this.productId = productId;
this.productName = productName;
this.price = price;
return productId;
// Store.java
// Parameterized constructor
this.storeId = storeId;
this.storeName = storeName;
products[productCount] = product;
productCount++;
} else {
System.out.println("Cannot add more products. Store inventory full.");
if (products[i].getProductId().equals(productId)) {
index = i;
removedProduct = products[i];
break;
if (index != -1) {
products[productCount - 1] = null;
productCount--;
return removedProduct;
if (productCount > 0) {
products[i].displayProductDetails();
} else {
// StoreProductApp.java
public class StoreProductApp {
store1.addProduct(product1);
store1.addProduct(product2);
store1.addProduct(product3);
store1.displayStoreDetails();
store2.displayStoreDetails();
if (transferredProduct != null) {
store2.addProduct(transferredProduct);
}
// Display updated store details
store1.displayStoreDetails();
store2.displayStoreDetails();
// Motherboard.java
// Parameterized constructor
this.model = model;
this.chipset = chipset;
this.socketType = socketType;
}
// Method to display motherboard details
// Computer.java
this.computerName = computerName;
this.manufacturer = manufacturer;
System.out.println("\nMotherboard Information:");
motherboard.displayMotherboardDetails();
// ComputerMotherboardApp.java
computer1.displayComputerDetails();
computer2.displayComputerDetails();
}
Question 9: Shape Hierarchy System (Inheritance)
Develop a Shape Hierarchy System that demonstrates inheritance, where different types of shapes
inherit from a base Shape class. The Shape class should be the parent class with attributes color
(String) and filled (boolean). It should include a constructor to initialize these attributes, getArea()
and getPerimeter() methods that return 0.0 by default, and a displayDetails() method. The Circle
class should extend Shape and add a radius (double) attribute. It should override getArea() and
getPerimeter() to calculate using the radius, and override displayDetails() to include circle-specific
information. The Rectangle class should also extend Shape and add width (double) and height
(double) attributes. It should override getArea(), getPerimeter(), and displayDetails() methods for
rectangle calculations. In the main method, create objects of both shape types, set their properties,
and display their details including area and perimeter.
// Shape.java
// Constructor
this.color = color;
this.filled = filled;
}
// Method to display shape details
// Circle.java
// Constructor
this.radius = radius;
@Override
@Override
@Override
// Rectangle.java
// Constructor
this.width = width;
this.height = height;
@Override
@Override
// ShapeApp.java
// Create a Circle
Circle circle = new Circle("Red", true, 5.0);
// Create a Rectangle
circle.displayDetails();
rectangle.displayDetails();
// Demonstrate polymorphism
shape1.displayDetails();
shape2.displayDetails();
}
Question 10: Calculator-Validator System (Dependency)
// NumberValidator.java
return num != 0;
}
// Calculator.java
// For demonstration purposes, we'll validate that inputs are in a reasonable range
return a + b;
// Subtract b from a
// For demonstration purposes, we'll validate that inputs are in a reasonable range
}
return a - b;
// For demonstration purposes, we'll validate that inputs are in a reasonable range
return a * b;
// Divide a by b
if (!validator.isNotZero(b)) {
}
// For demonstration purposes, we'll validate that inputs are in a reasonable range
return a / b;
if (!validator.isPositive(a)) {
return Math.sqrt(a);
// CalculatorApp.java
// Addition
try {
// Large numbers
} catch (Exception e) {
// Subtraction
try {
} catch (Exception e) {
// Multiplication
try {
// Division (valid)
try {
} catch (Exception e) {
try {
} catch (Exception e) {
try {
} catch (Exception e) {
}
// Square root of negative number (invalid)
try {
} catch (Exception e) {
o Guest has a reference to Hotel but can check in and check out
These examples provide additional practice with identifying and implementing the main types of
relationships in object-oriented programming, following the format of your lab sheet.