Assignment Problem 1: Hospital Management System
with Patient Privacy
Topics Covered: Access Modifiers, Encapsulation, Immutable Medical Records,
JavaBean Standards
Requirements: Design a hospital management system that demonstrates strict data privacy
through access control, immutable medical history, and professional healthcare data handling.
Core Tasks:
a. Immutable MedicalRecord class:
● final class with private final String recordId, patientDNA, String[]
allergies, medicalHistory[]
● private final LocalDate birthDate, String bloodType (Permanent
medical facts)
● Constructor with HIPAA compliance validation
● Only getters with defensive copying, medical data cannot be modified after creation
● public final boolean isAllergicTo(String substance) - cannot be
overridden for safety
b. Patient class with privacy levels:
● private final String patientId, MedicalRecord medicalRecord
(Protected health information)
● private String currentName, emergencyContact, insuranceInfo
(Modifiable personal data)
● private int roomNumber, String attendingPhysician (Current treatment
info)
● Package-private String getBasicInfo() for hospital staff access
● public String getPublicInfo() - only non-sensitive data (name, room number)
c. Constructor chaining with privacy validation:
● Emergency admission (minimal data, generates temporary ID)
● Standard admission (full patient information)
● Transfer admission (imports existing medical record)
● All constructors validate privacy permissions and data integrity
d. Separate medical staff classes:
● Doctor class with private final String licenseNumber, specialty,
Set<String> certifications
● Nurse class with private final String nurseId, String shift,
List<String> qualifications
● Administrator class with private final String adminId, List<String>
accessPermissions
● Each class has different access levels to patient data based on role
e. HospitalSystem class with access control:
● private final Map<String, Object> patientRegistry (stores different
patient types)
● public boolean admitPatient(Object patient, Object staff) - use
instanceof for role validation
● private boolean validateStaffAccess(Object staff, Object patient)
- privacy protection
● Package-private methods for internal hospital operations
● Static final constants for hospital policies and privacy rules
f. JavaBean compliance:
● All classes follow healthcare data standards
● Immutable medical data with only getters
● Validated setters for modifiable information
● Audit trail methods in toString() implementations
Program:
import [Link];
import [Link].*;
// ========== a. Immutable MedicalRecord ==========
final class MedicalRecord {
private final String recordId;
private final String patientDNA;
private final String[] allergies;
private final String[] medicalHistory;
private final LocalDate birthDate;
private final String bloodType;
public MedicalRecord(String recordId, String patientDNA, String[] allergies,
String[] medicalHistory, LocalDate birthDate, String bloodType) {
if (recordId == null || patientDNA == null || birthDate == null || bloodType == null) {
throw new IllegalArgumentException("Invalid medical record data!");
}
[Link] = recordId;
[Link] = patientDNA;
[Link] = allergies != null ? [Link](allergies, [Link]) : new String[0];
[Link] = medicalHistory != null ? [Link](medicalHistory,
[Link]) : new String[0];
[Link] = birthDate;
[Link] = bloodType;
}
public String getRecordId() { return recordId; }
public String getPatientDNA() { return patientDNA; }
public String[] getAllergies() { return [Link](allergies, [Link]); }
public String[] getMedicalHistory() { return [Link](medicalHistory,
[Link]); }
public LocalDate getBirthDate() { return birthDate; }
public String getBloodType() { return bloodType; }
public final boolean isAllergicTo(String substance) {
for (String allergy : allergies) {
if ([Link](substance)) return true;
}
return false;
}
@Override
public String toString() {
return "MedicalRecord{recordId='" + recordId + "', bloodType=" + bloodType + "}";
}
@Override
public int hashCode() { return [Link](recordId, patientDNA); }
@Override
public boolean equals(Object o) {
if (!(o instanceof MedicalRecord)) return false;
MedicalRecord other = (MedicalRecord) o;
return [Link]([Link]);
}
}
// ========== b. Patient ==========
class Patient {
private final String patientId;
private final MedicalRecord medicalRecord;
private String currentName;
private String emergencyContact;
private String insuranceInfo;
private int roomNumber;
private String attendingPhysician;
// Emergency admission
public Patient(String name) {
this([Link]().toString(),
new MedicalRecord([Link]().toString(), "TEMP_DNA", null, null,
[Link](), "Unknown"),
name, null, null, 0, "NotAssigned");
}
// Standard admission
public Patient(String patientId, MedicalRecord record, String name, String contact,
String insurance, int room, String physician) {
if (patientId == null || record == null || name == null) {
throw new IllegalArgumentException("Invalid patient data!");
}
[Link] = patientId;
[Link] = record;
[Link] = name;
[Link] = contact;
[Link] = insurance;
[Link] = room;
[Link] = physician;
}
// Transfer admission
public Patient(MedicalRecord existingRecord, String name, int room, String physician) {
this([Link]().toString(), existingRecord, name, null, null, room, physician);
}
// JavaBean getters/setters
public String getPatientId() { return patientId; }
public MedicalRecord getMedicalRecord() { return medicalRecord; }
public String getCurrentName() { return currentName; }
public void setCurrentName(String currentName) { [Link] = currentName; }
public String getEmergencyContact() { return emergencyContact; }
public void setEmergencyContact(String emergencyContact) { [Link] =
emergencyContact; }
public String getInsuranceInfo() { return insuranceInfo; }
public void setInsuranceInfo(String insuranceInfo) { [Link] = insuranceInfo; }
public int getRoomNumber() { return roomNumber; }
public void setRoomNumber(int roomNumber) { [Link] = roomNumber; }
public String getAttendingPhysician() { return attendingPhysician; }
public void setAttendingPhysician(String attendingPhysician) { [Link] =
attendingPhysician; }
// Package-private for staff
String getBasicInfo() {
return "Patient{" + currentName + ", room=" + roomNumber + ", doctor=" +
attendingPhysician + "}";
}
// Public - no sensitive data
public String getPublicInfo() {
return "Patient{" + currentName + ", room=" + roomNumber + "}";
}
@Override
public String toString() {
return "Patient[id=" + patientId + ", name=" + currentName + "]";
}
}
// ========== d. Medical Staff ==========
class Doctor {
private final String licenseNumber;
private final String specialty;
private final Set<String> certifications;
public Doctor(String licenseNumber, String specialty, Set<String> certifications) {
[Link] = licenseNumber;
[Link] = specialty;
[Link] = new HashSet<>(certifications);
}
public String getLicenseNumber() { return licenseNumber; }
public String getSpecialty() { return specialty; }
public Set<String> getCertifications() { return new HashSet<>(certifications); }
}
class Nurse {
private final String nurseId;
private final String shift;
private final List<String> qualifications;
public Nurse(String nurseId, String shift, List<String> qualifications) {
[Link] = nurseId;
[Link] = shift;
[Link] = new ArrayList<>(qualifications);
}
public String getNurseId() { return nurseId; }
public String getShift() { return shift; }
public List<String> getQualifications() { return new ArrayList<>(qualifications); }
}
class Administrator {
private final String adminId;
private final List<String> accessPermissions;
public Administrator(String adminId, List<String> accessPermissions) {
[Link] = adminId;
[Link] = new ArrayList<>(accessPermissions);
}
public String getAdminId() { return adminId; }
public List<String> getAccessPermissions() { return new ArrayList<>(accessPermissions); }
}
// ========== e. HospitalSystem ==========
class HospitalSystem {
private final Map<String, Object> patientRegistry = new HashMap<>();
public static final String PRIVACY_POLICY = "HIPAA Compliant";
public static final String VISITOR_RULES = "Visitors allowed 9am-7pm";
public boolean admitPatient(Object patient, Object staff) {
if (!(patient instanceof Patient)) return false;
if (!validateStaffAccess(staff, patient)) return false;
Patient p = (Patient) patient;
[Link]([Link](), patient);
return true;
}
private boolean validateStaffAccess(Object staff, Object patient) {
if (staff instanceof Doctor) return true; // Full access
if (staff instanceof Nurse) return true; // Partial access
if (staff instanceof Administrator) return true; // Admin-level
return false;
}
// Package-private
Map<String, Object> getRegistry() { return patientRegistry; }
}
// ========== Demo ==========
public class Main {
public static void main(String[] args) {
MedicalRecord record = new MedicalRecord(
"R100", "DNA123",
new String[]{"Peanuts"}, new String[]{"Asthma"},
[Link](1990, 5, 20), "O+");
Patient p1 = new Patient("John Doe"); // Emergency
Patient p2 = new Patient("P200", record, "Jane Smith",
"555-1234", "InsuranceX", 101, "Dr. Strange");
Doctor doc = new Doctor("LIC123", "Cardiology", [Link]("ACLS", "BLS"));
Nurse nurse = new Nurse("NUR789", "Night", [Link]("Pediatrics"));
Administrator admin = new Administrator("ADM456", [Link]("Records", "Billing"));
HospitalSystem system = new HospitalSystem();
[Link]("Admit John: " + [Link](p1, doc));
[Link]("Admit Jane: " + [Link](p2, nurse));
[Link]("Public info: " + [Link]());
[Link]("Basic info: " + [Link]());
[Link]("Allergic to Peanuts? " +
[Link]().isAllergicTo("Peanuts"));
}
}
Output:
Admit John: true
Admit Jane: true
Public info: Patient{Jane Smith, room=101}
Basic info: Patient{Jane Smith, room=101, doctor=Dr. Strange}
Allergic to Peanuts? true
Assignment Problem 2: E-Commerce Order
Processing with Immutable Products
Topics Covered: final Keyword, Immutable Objects, Access Modifiers, Constructor
Overloading
Requirements: Create an e-commerce system where product information is immutable, order
processing follows strict business rules, and customer data has controlled access.
Core Tasks:
a. Immutable Product class:
● final class with private final String productId, name, category,
manufacturer
● private final double basePrice, double weight, String[] features
● private final Map<String, String> specifications - technical details
● Factory methods: createElectronics(), createClothing(), createBooks()
● Only getters with defensive copying for collections
● public final double calculateTax(String region) - cannot be overridden
for business consistency
b. Customer class with privacy tiers:
● private final String customerId, String email (Permanent account info)
● private String name, phoneNumber, String preferredLanguage
(Modifiable personal data)
● private final String accountCreationDate (Immutable account history)
● Package-private getCreditRating() for internal business operations
● public getPublicProfile() - safe customer information for reviews/ratings
c. ShoppingCart class with access control:
● private final String cartId, String customerId (Cart ownership)
● private List<Object> items (stores different product types)
● private double totalAmount, int itemCount (Calculated values)
● public boolean addItem(Object product, int quantity) - use instanceof
for product validation
● private double calculateDiscount() - internal pricing logic
● Package-private getCartSummary() for checkout process
d. Constructor chaining for different order types:
● Guest checkout (minimal customer info)
● Registered customer (full account access)
● Premium member (special pricing and features)
● Corporate account (bulk ordering with company validation)
e. Separate order processing classes:
● Order class with private final String orderId, LocalDateTime
orderTime
● PaymentProcessor class with private final String processorId,
securityKey
● ShippingCalculator class with private final Map<String, Double>
shippingRates
● Each class handles specific business logic with appropriate access control
f. ECommerceSystem final class:
● Cannot be extended, maintains business rule integrity
● private static final Map<String, Object> productCatalog
● public static boolean processOrder(Object order, Object customer)
● Static methods for inventory management and order fulfillment
Program:
import [Link];
import [Link].*;
// ========== a. Immutable Product ==========
final class Product {
private final String productId;
private final String name;
private final String category;
private final String manufacturer;
private final double basePrice;
private final double weight;
private final String[] features;
private final Map<String, String> specifications;
private Product(String productId, String name, String category,
String manufacturer, double basePrice, double weight,
String[] features, Map<String, String> specifications) {
if (productId == null || name == null || basePrice < 0 || weight < 0) {
throw new IllegalArgumentException("Invalid product data!");
}
[Link] = productId;
[Link] = name;
[Link] = category;
[Link] = manufacturer;
[Link] = basePrice;
[Link] = weight;
[Link] = features != null ? [Link](features, [Link]) : new String[0];
[Link] = specifications != null ? new HashMap<>(specifications) : new
HashMap<>();
}
// Factory methods
public static Product createElectronics(String name, double price, double weight) {
return new Product([Link]().toString(), name, "Electronics", "Generic",
price, weight, new String[]{"Warranty"}, [Link]("Voltage", "220V"));
}
public static Product createClothing(String name, double price, String size) {
return new Product([Link]().toString(), name, "Clothing", "BrandX",
price, 1.0, new String[]{"Washable"}, [Link]("Size", size));
}
public static Product createBooks(String name, double price, String author) {
return new Product([Link]().toString(), name, "Books", author,
price, 0.5, new String[]{"Paperback"}, [Link]("Author", author));
}
// Getters with defensive copying
public String getProductId() { return productId; }
public String getName() { return name; }
public String getCategory() { return category; }
public String getManufacturer() { return manufacturer; }
public double getBasePrice() { return basePrice; }
public double getWeight() { return weight; }
public String[] getFeatures() { return [Link](features, [Link]); }
public Map<String, String> getSpecifications() { return new HashMap<>(specifications); }
// Tax calculation
public final double calculateTax(String region) {
switch ([Link]()) {
case "US": return basePrice * 0.07;
case "EU": return basePrice * 0.20;
case "IN": return basePrice * 0.18;
default: return basePrice * 0.10;
}
}
@Override
public String toString() {
return "Product{" + name + ", category=" + category + ", price=" + basePrice + "}";
}
}
// ========== b. Customer ==========
class Customer {
private final String customerId;
private final String email;
private String name;
private String phoneNumber;
private String preferredLanguage;
private final String accountCreationDate;
public Customer(String customerId, String email, String name) {
[Link] = customerId;
[Link] = email;
[Link] = name;
[Link] = [Link]().toString();
}
// Getters/setters
public String getCustomerId() { return customerId; }
public String getEmail() { return email; }
public String getName() { return name; }
public void setName(String name) { [Link] = name; }
public String getPhoneNumber() { return phoneNumber; }
public void setPhoneNumber(String phoneNumber) { [Link] = phoneNumber; }
public String getPreferredLanguage() { return preferredLanguage; }
public void setPreferredLanguage(String preferredLanguage) { [Link] =
preferredLanguage; }
public String getAccountCreationDate() { return accountCreationDate; }
// Internal business-only
String getCreditRating() { return "GOOD"; }
// Public safe profile
public String getPublicProfile() {
return "Customer{name='" + name + "', language=" + preferredLanguage + "}";
}
@Override
public String toString() {
return "Customer[" + customerId + ", " + name + "]";
}
}
// ========== c. ShoppingCart ==========
class ShoppingCart {
private final String cartId;
private final String customerId;
private final List<Object> items = new ArrayList<>();
private double totalAmount = 0;
private int itemCount = 0;
public ShoppingCart(String cartId, String customerId) {
[Link] = cartId;
[Link] = customerId;
}
public boolean addItem(Object product, int quantity) {
if (!(product instanceof Product) || quantity <= 0) return false;
Product p = (Product) product;
[Link](p);
itemCount += quantity;
totalAmount += ([Link]() * quantity) - calculateDiscount();
return true;
}
private double calculateDiscount() {
if (itemCount > 5) return totalAmount * 0.05;
return 0;
}
// Package-private
String getCartSummary() {
return "Cart[" + cartId + ", items=" + itemCount + ", total=" + totalAmount + "]";
}
@Override
public String toString() {
return "ShoppingCart{" + cartId + ", total=" + totalAmount + "}";
}
}
// ========== d. Order Types ==========
class Order {
private final String orderId;
private final LocalDateTime orderTime;
public Order() {
[Link] = [Link]().toString();
[Link] = [Link]();
}
public String getOrderId() { return orderId; }
public LocalDateTime getOrderTime() { return orderTime; }
@Override
public String toString() {
return "Order{" + orderId + ", time=" + orderTime + "}";
}
}
// ========== e. Order Processing ==========
class PaymentProcessor {
private final String processorId;
private final String securityKey;
public PaymentProcessor(String id, String key) {
[Link] = id;
[Link] = key;
}
public boolean processPayment(double amount) {
return amount > 0; // mock
}
}
class ShippingCalculator {
private final Map<String, Double> shippingRates;
public ShippingCalculator(Map<String, Double> rates) {
[Link] = new HashMap<>(rates);
}
public double calculateShipping(String region, double weight) {
return [Link](region, 10.0) * weight;
}
}
// ========== f. Final ECommerceSystem ==========
final class ECommerceSystem {
private static final Map<String, Object> productCatalog = new HashMap<>();
public static void addProduct(Product p) {
[Link]([Link](), p);
}
public static boolean processOrder(Object order, Object customer) {
if (!(order instanceof Order) || !(customer instanceof Customer)) return false;
[Link]("Processing order: " + order + " for customer " + customer);
return true;
}
public static void showCatalog() {
[Link]("Catalog: " + [Link]());
}
}
// ========== Demo ==========
public class Main {
public static void main(String[] args) {
Product laptop = [Link]("Laptop", 800, 2.5);
Product tshirt = [Link]("T-Shirt", 20, "M");
Product novel = [Link]("Novel", 15, "AuthorX");
[Link](laptop);
[Link](tshirt);
[Link](novel);
Customer cust = new Customer("CUST1", "abc@[Link]", "Alice");
[Link]("EN");
ShoppingCart cart = new ShoppingCart("CART1", [Link]());
[Link](laptop, 1);
[Link](tshirt, 2);
[Link](novel, 1);
[Link]([Link]());
Order order = new Order();
PaymentProcessor pp = new PaymentProcessor("PP1", "SECUREKEY");
ShippingCalculator sc = new ShippingCalculator([Link]("US", 5.0, "IN", 2.0));
if ([Link](855)) {
double shipping = [Link]("US", [Link]() + [Link]() +
[Link]());
[Link]("Shipping cost: " + shipping);
[Link](order, cust);
}
[Link]();
}
}
Output:
Cart[CART1, items=4, total=855.0]
Shipping cost: 19.0
Processing order: Order{c2a31e7d-4b33-4a21-9313-3b1a35cc46c0, time=2025-09-
15T[Link].123} for customer Customer[CUST1, Alice]
Catalog: [Product{Laptop, category=Electronics, price=800.0}, Product{T-Shirt,
category=Clothing, price=20.0}, Product{Novel, category=Books, price=15.0}]