0% found this document useful (0 votes)
8 views

oop_codes

The document outlines five object-oriented programming systems: Employee-Department (association), University-Professor (aggregation), Car-Engine (composition), Bank-Account (inheritance), and Order System (dependency). Each system demonstrates different relationships between classes, such as independent existence, containment, lifecycle dependency, inheritance, and temporary usage. The document provides code examples for each system, illustrating how to implement these relationships in Java.

Uploaded by

upekshawaragoda1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

oop_codes

The document outlines five object-oriented programming systems: Employee-Department (association), University-Professor (aggregation), Car-Engine (composition), Bank-Account (inheritance), and Order System (dependency). Each system demonstrates different relationships between classes, such as independent existence, containment, lifecycle dependency, inheritance, and temporary usage. The document provides code examples for each system, illustrating how to implement these relationships in Java.

Uploaded by

upekshawaragoda1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

Question 1: Employee-Department System (Association)

Develop an Employee-Department System where an Employee is associated with a Department, but


they exist independently. The Department class should represent a company department with
attributes departmentId and departmentName, both of type String. The class should include a
parameterized constructor to initialize these attributes and a method displayDepartmentDetails() to
print the department information. The Employee class should model an employee with attributes
employeeId, employeeName, and department (of type Department). It should have a default
constructor, a parameterized constructor to initialize employee details, a method
setDepartment(Department dept) to associate the employee with a department, and a
displayEmployeeDetails() method to print employee information along with department details. In
the main method, create a Department object and two Employee objects. Associate both employees
with the department and display the details of all employees.

public class Department {

private String departmentId;

private String departmentName;

// Parameterized constructor

public Department(String departmentId, String departmentName) {

this.departmentId = departmentId;

this.departmentName = departmentName;

// Method to display department details

public void displayDepartmentDetails() {

System.out.println("Department ID: " + departmentId);

System.out.println("Department Name: " + departmentName);

// Employee.java

public class Employee {


private String employeeId;

private String employeeName;

private Department department; // Association

// Default constructor

public Employee() {

// Parameterized constructor

public Employee(String employeeId, String employeeName) {

this.employeeId = employeeId;

this.employeeName = employeeName;

// Method to set department

public void setDepartment(Department department) {

this.department = department;

// Method to display employee details

public void displayEmployeeDetails() {

System.out.println("\n----- EMPLOYEE DETAILS -----");

System.out.println("Employee ID: " + employeeId);

System.out.println("Employee Name: " + employeeName);

if (department != null) {

System.out.println("\nDepartment Information:");
department.displayDepartmentDetails();

} else {

System.out.println("Not assigned to any department.");

// EmployeeDepartmentApp.java

public class EmployeeDepartmentApp {

public static void main(String[] args) {

// Create a Department object

Department itDepartment = new Department("D001", "Information Technology");

// Create Employee objects

Employee emp1 = new Employee("E001", "John Smith");

Employee emp2 = new Employee("E002", "Sarah Johnson");

// Associate employees with department

emp1.setDepartment(itDepartment);

emp2.setDepartment(itDepartment);

// Display employee details

emp1.displayEmployeeDetails();

emp2.displayEmployeeDetails();

}
Question 2: University-Professor System (Aggregation)

Develop a University-Professor System where a University contains multiple Professors, but


Professors can exist independently. The Professor class should represent a university professor with
attributes professorId and professorName, both of type String. The class should include a
parameterized constructor to initialize these attributes and a method displayProfessorDetails() to
print professor information. The University class should model a university that can contain up to
five professors. It should include attributes universityName (String) and an array of Professor objects
(size 5), along with an integer to track the number of professors. The class should provide a
constructor to set the university name, a method addProfessor(Professor prof) to add a professor to
the array, and a displayUniversityDetails() method to print university information and all professors'
details. In the main method, create a University object and three Professor objects, add the
professors to the university, and display the university details.

// Professor.java

public class Professor {

private String professorId;

private String professorName;

// Parameterized constructor

public Professor(String professorId, String professorName) {

this.professorId = professorId;

this.professorName = professorName;

// Method to display professor details

public void displayProfessorDetails() {

System.out.println("Professor ID: " + professorId);

System.out.println("Professor Name: " + professorName);

// University.java
public class University {

private String universityName;

private Professor[] professors = new Professor[5]; // Aggregation

private int professorCount = 0;

// Constructor to set university name

public University(String universityName) {

this.universityName = universityName;

// Method to add professor to the university

public void addProfessor(Professor prof) {

if (professorCount < professors.length) {

professors[professorCount] = prof;

professorCount++;

System.out.println("Professor added to university successfully.");

} else {

System.out.println("Cannot add more professors. Maximum limit reached.");

// Method to display university details

public void displayUniversityDetails() {

System.out.println("\n----- UNIVERSITY DETAILS -----");

System.out.println("University Name: " + universityName);

System.out.println("Number of Professors: " + professorCount);


if (professorCount > 0) {

System.out.println("\n----- PROFESSORS -----");

for (int i = 0; i < professorCount; i++) {

System.out.println("\nProfessor " + (i+1) + ":");

professors[i].displayProfessorDetails();

} else {

System.out.println("No professors at this university yet.");

// UniversityProfessorApp.java

public class UniversityProfessorApp {

public static void main(String[] args) {

// Create University object

University harvard = new University("Harvard University");

// Create Professor objects

Professor prof1 = new Professor("P001", "Dr. Robert Williams");

Professor prof2 = new Professor("P002", "Dr. Jennifer Parker");

Professor prof3 = new Professor("P003", "Dr. Michael Chen");

// Add professors to university

harvard.addProfessor(prof1);

harvard.addProfessor(prof2);

harvard.addProfessor(prof3);
// Display university details

harvard.displayUniversityDetails();

Question 3: Car-Engine System (Composition)

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

public class Engine {

private String engineType;

private int horsepower;

// Parameterized constructor

public Engine(String engineType, int horsepower) {

this.engineType = engineType;

this.horsepower = horsepower;

// Method to display engine details

public void displayEngineDetails() {

System.out.println("Engine Type: " + engineType);

System.out.println("Horsepower: " + horsepower + " HP");

}
}

// Car.java

public class Car {

private String carModel;

private Engine engine; // Composition

// Constructor that creates a new Engine (composition)

public Car(String carModel, String engineType, int horsepower) {

this.carModel = carModel;

this.engine = new Engine(engineType, horsepower); // Engine lifecycle tied to Car

// Method to display car details

public void displayCarDetails() {

System.out.println("\n----- CAR DETAILS -----");

System.out.println("Car Model: " + carModel);

System.out.println("\nEngine Information:");

engine.displayEngineDetails();

// CarEngineApp.java

public class CarEngineApp {

public static void main(String[] args) {

// Create Car objects with engines

Car car1 = new Car("Toyota Camry", "V6", 268);


Car car2 = new Car("Tesla Model 3", "Electric", 283);

// Display car details

car1.displayCarDetails();

car2.displayCarDetails();

Question 4: Bank-Account System (Inheritance)

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

public class Account {

protected String accountNumber;

protected double balance;

// Constructor

public Account(String accountNumber, double initialBalance) {

this.accountNumber = accountNumber;

this.balance = initialBalance;

// Method to deposit money


public void deposit(double amount) {

if (amount > 0) {

balance += amount;

System.out.println("$" + amount + " deposited successfully.");

} else {

System.out.println("Invalid deposit amount.");

// Method to withdraw money

public void withdraw(double amount) {

if (amount > 0 && amount <= balance) {

balance -= amount;

System.out.println("$" + amount + " withdrawn successfully.");

} else {

System.out.println("Insufficient funds or invalid amount.");

// Method to display account details

public void displayAccountDetails() {

System.out.println("\n----- ACCOUNT DETAILS -----");

System.out.println("Account Number: " + accountNumber);

System.out.println("Balance: $" + balance);

}
// SavingsAccount.java

public class SavingsAccount extends Account {

private double interestRate;

// Constructor

public SavingsAccount(String accountNumber, double initialBalance, double interestRate) {

super(accountNumber, initialBalance); // Call parent constructor

this.interestRate = interestRate;

// Method to calculate interest

public double calculateInterest() {

double interest = balance * interestRate / 100;

System.out.println("Interest calculated: $" + interest);

return interest;

// Apply interest to balance

public void applyInterest() {

double interest = calculateInterest();

deposit(interest);

// Override display method to include interest rate

@Override

public void displayAccountDetails() {

super.displayAccountDetails(); // Call parent method


System.out.println("Account Type: Savings Account");

System.out.println("Interest Rate: " + interestRate + "%");

// CheckingAccount.java

public class CheckingAccount extends Account {

private double overdraftLimit;

// Constructor

public CheckingAccount(String accountNumber, double initialBalance, double overdraftLimit) {

super(accountNumber, initialBalance); // Call parent constructor

this.overdraftLimit = overdraftLimit;

// Override withdraw method to allow overdraft

@Override

public void withdraw(double amount) {

if (amount > 0 && amount <= (balance + overdraftLimit)) {

balance -= amount;

System.out.println("$" + amount + " withdrawn successfully.");

if (balance < 0) {

System.out.println("Account overdrawn! Current balance: $" + balance);

} else {

System.out.println("Withdrawal amount exceeds overdraft limit or is invalid.");

}
}

// Override display method to include overdraft limit

@Override

public void displayAccountDetails() {

super.displayAccountDetails(); // Call parent method

System.out.println("Account Type: Checking Account");

System.out.println("Overdraft Limit: $" + overdraftLimit);

// BankAccountApp.java

public class BankAccountApp {

public static void main(String[] args) {

// Create a SavingsAccount

SavingsAccount savings = new SavingsAccount("SA001", 1000.0, 2.5);

// Create a CheckingAccount

CheckingAccount checking = new CheckingAccount("CA001", 500.0, 200.0);

// Perform transactions

System.out.println("\n----- SAVINGS ACCOUNT TRANSACTIONS -----");

savings.deposit(500.0);

savings.withdraw(200.0);

savings.applyInterest();

System.out.println("\n----- CHECKING ACCOUNT TRANSACTIONS -----");


checking.deposit(300.0);

checking.withdraw(900.0); // This will use the overdraft

// Display account details

savings.displayAccountDetails();

checking.displayAccountDetails();

Question 5: OrderSystem (Dependency)

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.

public class Order {

private String orderId;

private String customerName;

private double totalAmount;

// Parameterized constructor

public Order(String orderId, String customerName, double totalAmount) {

this.orderId = orderId;

this.customerName = customerName;

this.totalAmount = totalAmount;

}
// Getters

public String getOrderId() {

return orderId;

public String getCustomerName() {

return customerName;

public double getTotalAmount() {

return totalAmount;

// Method to display order details

public void displayOrderDetails() {

System.out.println("Order ID: " + orderId);

System.out.println("Customer Name: " + customerName);

System.out.println("Total Amount: $" + totalAmount);

// OrderProcessor.java

public class OrderProcessor {

// Process an order (dependency - uses Order temporarily)

public void processOrder(Order order) {

System.out.println("\n----- PROCESSING ORDER -----");

System.out.println("Validating order: " + order.getOrderId());


if (order.getTotalAmount() <= 0) {

System.out.println("Invalid order amount!");

return;

double tax = calculateTax(order.getTotalAmount());

System.out.println("Order validated successfully.");

System.out.println("Tax calculated: $" + tax);

System.out.println("Total with tax: $" + (order.getTotalAmount() + tax));

// Generate invoice for an order (dependency - uses Order temporarily)

public void generateInvoice(Order order) {

System.out.println("\n----- INVOICE -----");

System.out.println("Invoice for Order: " + order.getOrderId());

System.out.println("Customer: " + order.getCustomerName());

double subtotal = order.getTotalAmount();

double tax = calculateTax(subtotal);

double total = subtotal + tax;

System.out.println("Subtotal: $" + subtotal);

System.out.println("Tax (8%): $" + tax);

System.out.println("Total: $" + total);

System.out.println("Thank you for your business!");

}
// Helper method to calculate tax

private double calculateTax(double amount) {

return amount * 0.08; // 8% tax rate

// OrderSystemApp.java

public class OrderSystemApp {

public static void main(String[] args) {

// Create Order object

Order order = new Order("ORD1001", "John Doe", 150.75);

// Create OrderProcessor

OrderProcessor processor = new OrderProcessor();

// Display order details

System.out.println("----- ORDER DETAILS -----");

order.displayOrderDetails();

// Process the order

processor.processOrder(order);

// Generate invoice

processor.generateInvoice(order);

}
Summary of Object-Oriented Relationships in the Questions

Each question demonstrates a different type of relationship in object-oriented programming:

1. Question 1: Employee-Department System (Association)

o Shows association where Employee and Department are connected but exist
independently

o Employee has a reference to Department but Department doesn't track Employees

o Neither class controls the lifecycle of the other

2. Question 2: University-Professor System (Aggregation)

o Shows aggregation where University contains Professors

o University has references to Professor objects

o Professors can exist independently of the University

o A "has-a" relationship with independent parts

3. Question 3: Car-Engine System (Composition)

o Shows composition where Car contains an Engine

o Engine is created when Car is created

o Engine's lifecycle is dependent on Car's lifecycle

o A "part-of" relationship with strong ownership

4. Question 4: Bank-Account System (Inheritance)

o Shows inheritance where SavingsAccount and CheckingAccount inherit from


Account

o Demonstrates "is-a" relationship

o Child classes extend and specialize behavior of the parent class

o Demonstrates method overriding

5. Question 5: OrderSystem (Dependency)

o Shows dependency where OrderProcessor temporarily uses Order objects

o OrderProcessor doesn't store Order references as attributes

o Methods use Order objects only during execution

o A "uses-a" temporary relationship


5 Additional Object-Oriented Programming Relationship Questions

I'll create 5 more questions that demonstrate the different relationships in object-oriented
programming, following the same format as before.

Question 6: Hotel-Guest System (Association)

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.

public class Hotel {

private String hotelId;

private String hotelName;

// Parameterized constructor

public Hotel(String hotelId, String hotelName) {

this.hotelId = hotelId;

this.hotelName = hotelName;

// Method to display hotel details

public void displayHotelDetails() {

System.out.println("Hotel ID: " + hotelId);

System.out.println("Hotel Name: " + hotelName);

// Guest.java
public class Guest {

private String guestId;

private String guestName;

private Hotel currentHotel; // Association

// Default constructor

public Guest() {

// Parameterized constructor

public Guest(String guestId, String guestName) {

this.guestId = guestId;

this.guestName = guestName;

// Method to check in to a hotel

public void checkIn(Hotel hotel) {

this.currentHotel = hotel;

System.out.println(guestName + " checked in to " + hotel.getClass().getName());

// Method to check out from hotel

public void checkOut() {

if (currentHotel != null) {

System.out.println(guestName + " checked out from hotel");

this.currentHotel = null;

} else {
System.out.println(guestName + " is not currently staying at any hotel");

// Method to display guest details

public void displayGuestDetails() {

System.out.println("\n----- GUEST DETAILS -----");

System.out.println("Guest ID: " + guestId);

System.out.println("Guest Name: " + guestName);

if (currentHotel != null) {

System.out.println("\nCurrently staying at:");

currentHotel.displayHotelDetails();

} else {

System.out.println("Not currently staying at any hotel");

// HotelGuestApp.java

public class HotelGuestApp {

public static void main(String[] args) {

// Create a Hotel object

Hotel grandHotel = new Hotel("H001", "Grand Hotel");

// Create Guest objects

Guest guest1 = new Guest("G001", "Alex Johnson");


Guest guest2 = new Guest("G002", "Maria Garcia");

// Check in guests to hotel

guest1.checkIn(grandHotel);

guest2.checkIn(grandHotel);

// Display guest details

System.out.println("\n----- AFTER CHECK-IN -----");

guest1.displayGuestDetails();

guest2.displayGuestDetails();

// Check out one guest

guest1.checkOut();

// Display updated details

System.out.println("\n----- AFTER CHECK-OUT -----");

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

public class Product {

private String productId;

private String productName;

private double price;

// Parameterized constructor

public Product(String productId, String productName, double price) {

this.productId = productId;

this.productName = productName;

this.price = price;

// Getter for productId

public String getProductId() {

return productId;

// Method to display product details


public void displayProductDetails() {

System.out.println("Product ID: " + productId);

System.out.println("Product Name: " + productName);

System.out.println("Price: $" + price);

// Store.java

public class Store {

private String storeId;

private String storeName;

private Product[] products = new Product[10]; // Aggregation

private int productCount = 0;

// Parameterized constructor

public Store(String storeId, String storeName) {

this.storeId = storeId;

this.storeName = storeName;

// Method to add product to store

public void addProduct(Product product) {

if (productCount < products.length) {

products[productCount] = product;

productCount++;

System.out.println("Product " + product.getProductId() + " added to store " + storeName);

} else {
System.out.println("Cannot add more products. Store inventory full.");

// Method to remove product from store

public Product removeProduct(String productId) {

Product removedProduct = null;

int index = -1;

// Find the product

for (int i = 0; i < productCount; i++) {

if (products[i].getProductId().equals(productId)) {

index = i;

removedProduct = products[i];

break;

// Remove the product if found

if (index != -1) {

// Shift products to fill the gap

for (int i = index; i < productCount - 1; i++) {

products[i] = products[i + 1];

products[productCount - 1] = null;

productCount--;

System.out.println("Product " + productId + " removed from store " + storeName);


} else {

System.out.println("Product " + productId + " not found in store " + storeName);

return removedProduct;

// Method to display store details

public void displayStoreDetails() {

System.out.println("\n----- STORE DETAILS -----");

System.out.println("Store ID: " + storeId);

System.out.println("Store Name: " + storeName);

System.out.println("Product Count: " + productCount);

if (productCount > 0) {

System.out.println("\n----- STORE INVENTORY -----");

for (int i = 0; i < productCount; i++) {

System.out.println("\nProduct " + (i+1) + ":");

products[i].displayProductDetails();

} else {

System.out.println("No products in store inventory.");

// StoreProductApp.java
public class StoreProductApp {

public static void main(String[] args) {

// Create Store objects

Store store1 = new Store("S001", "Main Street Store");

Store store2 = new Store("S002", "Downtown Branch");

// Create Product objects

Product product1 = new Product("P001", "Laptop", 899.99);

Product product2 = new Product("P002", "Smartphone", 499.99);

Product product3 = new Product("P003", "Headphones", 79.99);

// Add products to store1

store1.addProduct(product1);

store1.addProduct(product2);

store1.addProduct(product3);

// Display initial store details

System.out.println("\n----- INITIAL STORE DETAILS -----");

store1.displayStoreDetails();

store2.displayStoreDetails();

// Transfer product2 from store1 to store2

System.out.println("\n----- TRANSFERRING PRODUCT -----");

Product transferredProduct = store1.removeProduct("P002");

if (transferredProduct != null) {

store2.addProduct(transferredProduct);

}
// Display updated store details

System.out.println("\n----- UPDATED STORE DETAILS -----");

store1.displayStoreDetails();

store2.displayStoreDetails();

Question 8: Computer-Motherboard System (Composition)

Develop a Computer-Motherboard System that demonstrates composition, where a Computer


contains a Motherboard that cannot exist without the Computer. The Motherboard class should
represent a computer motherboard with attributes model, chipset, and socketType, all of type
String. It should include a parameterized constructor to initialize these attributes and a method
displayMotherboardDetails() to print motherboard information. The Computer class should model a
computer that must have a motherboard. It should include attributes computerName (String),
manufacturer (String), and motherboard (Motherboard). The class should have a constructor that
creates a new Motherboard as part of its initialization, making the Motherboard's lifecycle
dependent on the Computer. It should also include a displayComputerDetails() method to print
computer information and motherboard details. In the main method, create two Computer objects
with different motherboard specifications and display their details.

// Motherboard.java

public class Motherboard {

private String model;

private String chipset;

private String socketType;

// Parameterized constructor

public Motherboard(String model, String chipset, String socketType) {

this.model = model;

this.chipset = chipset;

this.socketType = socketType;

}
// Method to display motherboard details

public void displayMotherboardDetails() {

System.out.println("Motherboard Model: " + model);

System.out.println("Chipset: " + chipset);

System.out.println("Socket Type: " + socketType);

// Computer.java

public class Computer {

private String computerName;

private String manufacturer;

private Motherboard motherboard; // Composition

// Constructor that creates a new Motherboard (composition)

public Computer(String computerName, String manufacturer, String motherboardModel,

String chipset, String socketType) {

this.computerName = computerName;

this.manufacturer = manufacturer;

// Create the motherboard as part of the computer - lifecycle dependency

this.motherboard = new Motherboard(motherboardModel, chipset, socketType);

// Method to display computer details

public void displayComputerDetails() {

System.out.println("\n----- COMPUTER DETAILS -----");


System.out.println("Computer Name: " + computerName);

System.out.println("Manufacturer: " + manufacturer);

System.out.println("\nMotherboard Information:");

motherboard.displayMotherboardDetails();

// ComputerMotherboardApp.java

public class ComputerMotherboardApp {

public static void main(String[] args) {

// Create Computer objects with motherboards

Computer computer1 = new Computer("WorkStation Pro", "Dell",

"Z590", "Intel Z590", "LGA1200");

Computer computer2 = new Computer("GamingRig X1", "Custom Build",

"ROG Maximus", "AMD X570", "AM4");

// Display computer details

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

public class Shape {

protected String color;

protected boolean filled;

// Constructor

public Shape(String color, boolean filled) {

this.color = color;

this.filled = filled;

// Method to calculate area (default implementation)

public double getArea() {

return 0.0; // Default implementation

// Method to calculate perimeter (default implementation)

public double getPerimeter() {

return 0.0; // Default implementation

}
// Method to display shape details

public void displayDetails() {

System.out.println("Color: " + color);

System.out.println("Filled: " + (filled ? "Yes" : "No"));

// Circle.java

public class Circle extends Shape {

private double radius;

// Constructor

public Circle(String color, boolean filled, double radius) {

super(color, filled); // Call parent constructor

this.radius = radius;

// Override getArea for circle

@Override

public double getArea() {

return Math.PI * radius * radius;

// Override getPerimeter for circle

@Override

public double getPerimeter() {


return 2 * Math.PI * radius;

// Override displayDetails to include circle information

@Override

public void displayDetails() {

System.out.println("\n----- CIRCLE DETAILS -----");

super.displayDetails(); // Call parent method

System.out.println("Radius: " + radius);

System.out.println("Area: " + String.format("%.2f", getArea()));

System.out.println("Perimeter: " + String.format("%.2f", getPerimeter()));

// Rectangle.java

public class Rectangle extends Shape {

private double width;

private double height;

// Constructor

public Rectangle(String color, boolean filled, double width, double height) {

super(color, filled); // Call parent constructor

this.width = width;

this.height = height;

// Override getArea for rectangle


@Override

public double getArea() {

return width * height;

// Override getPerimeter for rectangle

@Override

public double getPerimeter() {

return 2 * (width + height);

// Override displayDetails to include rectangle information

@Override

public void displayDetails() {

System.out.println("\n----- RECTANGLE DETAILS -----");

super.displayDetails(); // Call parent method

System.out.println("Width: " + width);

System.out.println("Height: " + height);

System.out.println("Area: " + String.format("%.2f", getArea()));

System.out.println("Perimeter: " + String.format("%.2f", getPerimeter()));

// ShapeApp.java

public class ShapeApp {

public static void main(String[] args) {

// Create a Circle
Circle circle = new Circle("Red", true, 5.0);

// Create a Rectangle

Rectangle rectangle = new Rectangle("Blue", false, 4.0, 6.0);

// Display shape details

circle.displayDetails();

rectangle.displayDetails();

// Demonstrate polymorphism

System.out.println("\n----- DEMONSTRATING POLYMORPHISM -----");

Shape shape1 = new Circle("Green", true, 3.0);

Shape shape2 = new Rectangle("Yellow", true, 2.0, 8.0);

shape1.displayDetails();

shape2.displayDetails();

}
Question 10: Calculator-Validator System (Dependency)

Develop a Calculator-Validator System where a Calculator class uses a NumberValidator object


temporarily to validate inputs before performing calculations. The NumberValidator class should be
responsible for validating numeric inputs with methods isPositive(double num), isNegative(double
num), and isInRange(double num, double min, double max). The Calculator class should perform
mathematical operations but depend on the NumberValidator to check inputs first. It should include
methods add(double a, double b), subtract(double a, double b), multiply(double a, double b), and
divide(double a, double b), each of which creates a temporary NumberValidator to validate inputs
before performing calculations. These methods should demonstrate a dependency relationship by
using the NumberValidator only during method execution. In the main method, create a Calculator
object and use it to perform various operations with both valid and invalid inputs.

// NumberValidator.java

public class NumberValidator {

// Check if number is positive

public boolean isPositive(double num) {

return num > 0;

// Check if number is negative

public boolean isNegative(double num) {

return num < 0;

// Check if number is in range [min, max]

public boolean isInRange(double num, double min, double max) {

return num >= min && num <= max;

// Check if number is not zero (for division)

public boolean isNotZero(double num) {

return num != 0;
}

// Calculator.java

public class Calculator {

// Add two numbers

public double add(double a, double b) {

// Create temporary validator (dependency)

NumberValidator validator = new NumberValidator();

// For demonstration purposes, we'll validate that inputs are in a reasonable range

if (!validator.isInRange(a, -1000, 1000) || !validator.isInRange(b, -1000, 1000)) {

System.out.println("Warning: Numbers are outside the recommended range!");

return a + b;

// Subtract b from a

public double subtract(double a, double b) {

// Create temporary validator (dependency)

NumberValidator validator = new NumberValidator();

// For demonstration purposes, we'll validate that inputs are in a reasonable range

if (!validator.isInRange(a, -1000, 1000) || !validator.isInRange(b, -1000, 1000)) {

System.out.println("Warning: Numbers are outside the recommended range!");

}
return a - b;

// Multiply two numbers

public double multiply(double a, double b) {

// Create temporary validator (dependency)

NumberValidator validator = new NumberValidator();

// For demonstration purposes, we'll validate that inputs are in a reasonable range

if (!validator.isInRange(a, -1000, 1000) || !validator.isInRange(b, -1000, 1000)) {

System.out.println("Warning: Numbers are outside the recommended range!");

return a * b;

// Divide a by b

public double divide(double a, double b) {

// Create temporary validator (dependency)

NumberValidator validator = new NumberValidator();

// Validate divisor is not zero

if (!validator.isNotZero(b)) {

throw new ArithmeticException("Cannot divide by zero!");

}
// For demonstration purposes, we'll validate that inputs are in a reasonable range

if (!validator.isInRange(a, -1000, 1000) || !validator.isInRange(b, -1000, 1000)) {

System.out.println("Warning: Numbers are outside the recommended range!");

return a / b;

// Square root with validation

public double squareRoot(double a) {

// Create temporary validator (dependency)

NumberValidator validator = new NumberValidator();

// Validate number is positive

if (!validator.isPositive(a)) {

throw new IllegalArgumentException("Cannot take square root of negative number!");

return Math.sqrt(a);

// CalculatorApp.java

public class CalculatorApp {

public static void main(String[] args) {

// Create Calculator object

Calculator calculator = new Calculator();


System.out.println("----- CALCULATOR OPERATIONS -----");

// Addition

try {

double result = calculator.add(10.5, 5.5);

System.out.println("10.5 + 5.5 = " + result);

// Large numbers

result = calculator.add(2000, 3000);

System.out.println("2000 + 3000 = " + result);

} catch (Exception e) {

System.out.println("Addition error: " + e.getMessage());

// Subtraction

try {

double result = calculator.subtract(20.0, 7.5);

System.out.println("20.0 - 7.5 = " + result);

} catch (Exception e) {

System.out.println("Subtraction error: " + e.getMessage());

// Multiplication

try {

double result = calculator.multiply(4.0, 5.0);

System.out.println("4.0 * 5.0 = " + result);


} catch (Exception e) {

System.out.println("Multiplication error: " + e.getMessage());

// Division (valid)

try {

double result = calculator.divide(10.0, 2.0);

System.out.println("10.0 / 2.0 = " + result);

} catch (Exception e) {

System.out.println("Division error: " + e.getMessage());

// Division by zero (invalid)

try {

double result = calculator.divide(10.0, 0.0);

System.out.println("10.0 / 0.0 = " + result);

} catch (Exception e) {

System.out.println("Division error: " + e.getMessage());

// Square root (valid)

try {

double result = calculator.squareRoot(16.0);

System.out.println("√16.0 = " + result);

} catch (Exception e) {

System.out.println("Square root error: " + e.getMessage());

}
// Square root of negative number (invalid)

try {

double result = calculator.squareRoot(-4.0);

System.out.println("√-4.0 = " + result);

} catch (Exception e) {

System.out.println("Square root error: " + e.getMessage());

Summary of Object-Oriented Relationships in the Additional Questions

These 5 new questions demonstrate different types of relationships in object-oriented


programming:

1. Question 6: Hotel-Guest System (Association)

o Shows association where Guest can be associated with a Hotel temporarily

o Guest has a reference to Hotel but can check in and check out

o Neither class controls the lifecycle of the other

o Demonstrates temporary and optional association

2. Question 7: Store-Product System (Aggregation)

o Shows aggregation where Store contains Products

o Store has references to Product objects in an array

o Products can exist independently and can be transferred between stores

o A "has-a" relationship with independent parts that can be shared

3. Question 8: Computer-Motherboard System (Composition)

o Shows composition where Computer contains a Motherboard

o Motherboard is created when Computer is created

o Motherboard's lifecycle is tied to the Computer's lifecycle

o A strong "part-of" relationship with complete ownership


4. Question 9: Shape Hierarchy System (Inheritance)

o Shows inheritance where Circle and Rectangle inherit from Shape

o Demonstrates "is-a" relationship with method overriding

o Child classes extend and specialize behavior of the parent class

o Shows polymorphism through the parent class reference

5. Question 10: Calculator-Validator System (Dependency)

o Shows dependency where Calculator temporarily uses NumberValidator

o Calculator creates validator objects locally within methods

o Calculator depends on validator functionality but doesn't store references

o A "uses-a" temporary relationship for validation purposes

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.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy