Welcome to the Nested Objects exercises! This topic focuses on understanding how objects can contain other objects as fields, creating complex data structures and relationships between different classes.
- Creating classes that contain other objects as fields
- Understanding object composition and aggregation
- Working with nested object structures and navigation
- Managing relationships between multiple objects
- Designing classes that work together to solve complex problems
- Understanding object ownership and lifecycle management
These exercises focus on building complex systems where objects contain and interact with other objects. You'll learn to design classes that work together to model real-world scenarios.
Classes: Address, Person
Create a Person class that contains an Address object.
Address Requirements:
- Fields:
String street,String city,String state,String zipCode - Constructor: Takes all fields as parameters
- Methods:
getFullAddress()- Return formatted address stringisInState(String state)- Check if address is in given statetoString()- Return readable address format
Person Requirements:
- Fields:
String name,int age,Address homeAddress,Address workAddress(can be null) - Constructor: Takes name, age, and home address
- Methods:
setWorkAddress(Address workAddress)- Set work addressgetDistanceToWork()- Return 0.0 if same city, 10.0 if different city, 50.0 if different staterelocate(Address newAddress)- Change home addressgetAddressSummary()- Return string with both addresseslivesAndWorksInSameState()- Return true if both addresses in same state
Classes: Course, Student, University
Create a university system with students enrolled in courses.
Course Requirements:
- Fields:
String courseCode,String courseName,int credits,ArrayList<Student> enrolledStudents - Constructor: Takes code, name, and credits
- Methods:
enrollStudent(Student student)- Add student to course (max 30 students)dropStudent(Student student)- Remove student from coursegetEnrollmentCount()- Return number of enrolled studentsgetStudentNames()- Return ArrayList of student nameshasStudent(String studentName)- Check if student is enrolledgetAverageGPA()- Return average GPA of enrolled students
Student Requirements:
- Fields:
String name,String studentId,double gpa,ArrayList<Course> enrolledCourses - Constructor: Takes name, student ID, and GPA
- Methods:
enrollInCourse(Course course)- Add course (max 6 courses)dropCourse(Course course)- Remove coursegetTotalCredits()- Sum credits from all coursesgetCourseList()- Return ArrayList of course namesisFullTimeStudent()- Return true if >= 12 creditstoString()- Return student info with courses
University Requirements:
- Fields:
String name,ArrayList<Student> students,ArrayList<Course> courses - Constructor: Takes university name
- Methods:
addStudent(Student student)- Add student to universityaddCourse(Course course)- Add course to universityfindStudent(String studentId)- Return student or nullfindCourse(String courseCode)- Return course or nullgetUniversityStats()- Return string with total students, courses, enrollmentsgetStudentsInCourse(String courseCode)- Return list of students in course
Classes: Room, Floor, Building
Create a building management system with nested structure.
Room Requirements:
- Fields:
String roomNumber,String roomType,int capacity,boolean isOccupied - Constructor: Takes room number, type, and capacity
- Methods:
occupyRoom()- Set as occupied if not already occupiedvacateRoom()- Set as vacantcanAccommodate(int people)- Check if room can fit peoplegetRoomInfo()- Return formatted room informationtoString()- Return "Room [number]: [type] (capacity: [capacity])"
Floor Requirements:
- Fields:
int floorNumber,ArrayList<Room> rooms,String floorType - Constructor: Takes floor number and type
- Methods:
addRoom(Room room)- Add room to floorremoveRoom(String roomNumber)- Remove room by numberfindRoom(String roomNumber)- Return room or nullgetAvailableRooms()- Return ArrayList of unoccupied roomsgetTotalCapacity()- Sum capacity of all roomsgetOccupancyRate()- Return percentage of occupied roomsgetFloorSummary()- Return string with floor stats
Building Requirements:
- Fields:
String buildingName,String address,ArrayList<Floor> floors - Constructor: Takes building name and address
- Methods:
addFloor(Floor floor)- Add floor to buildingremoveFloor(int floorNumber)- Remove floor by numberfindFloor(int floorNumber)- Return floor or nullfindRoom(String roomNumber)- Search all floors for roomgetBuildingStats()- Return comprehensive building statisticsgetAllAvailableRooms()- Return all unoccupied rooms in buildingreserveRoom(String roomNumber)- Find and occupy specific room
Classes: Transaction, Account, Customer, Bank
Create a banking system with nested financial objects.
Transaction Requirements:
- Fields:
String transactionId,String type,double amount,String date,String description - Constructor: Takes all fields
- Methods:
isDebit()- Return true if type is "DEBIT"isCredit()- Return true if type is "CREDIT"getTransactionSummary()- Return formatted transaction stringtoString()- Return transaction details
Account Requirements:
- Fields:
String accountNumber,String accountType,double balance,ArrayList<Transaction> transactions - Constructor: Takes account number and type, balance starts at 0
- Methods:
deposit(double amount, String description)- Add money, create transactionwithdraw(double amount, String description)- Remove money if sufficient funds, create transactiongetBalance()- Return current balancegetTransactionHistory()- Return copy of transactions listgetTransactionCount()- Return number of transactionsgetMonthlyStatement()- Return string summary of recent transactionscalculateInterest(double rate)- Return interest amount for current balance
Customer Requirements:
- Fields:
String customerId,String name,String email,ArrayList<Account> accounts - Constructor: Takes customer ID, name, and email
- Methods:
addAccount(Account account)- Add account to customerremoveAccount(String accountNumber)- Remove account by numberfindAccount(String accountNumber)- Return account or nullgetTotalBalance()- Sum balances of all accountsgetAccountSummary()- Return string with all account infohasAccount(String accountNumber)- Check if customer has accounttransferBetweenAccounts(String fromAccount, String toAccount, double amount)- Transfer within customer accounts
Bank Requirements:
- Fields:
String bankName,ArrayList<Customer> customers,HashMap<String, Account> allAccounts - Constructor: Takes bank name
- Methods:
addCustomer(Customer customer)- Add customer to bankfindCustomer(String customerId)- Return customer or nullfindAccount(String accountNumber)- Return account from any customergetTotalDeposits()- Sum all account balancesgetCustomerCount()- Return number of customersgetAccountCount()- Return total number of accountsgetBankReport()- Return comprehensive bank statisticsprocessInterPayment(String fromAccount, String toAccount, double amount)- Transfer between any accounts
Classes: Item, OrderLine, Order, OrderManager
Create an e-commerce order system with nested product relationships.
Item Requirements:
- Fields:
String itemId,String name,double price,int stockQuantity - Constructor: Takes all fields
- Methods:
reduceStock(int quantity)- Decrease stock if availableincreaseStock(int quantity)- Add to stockisInStock(int quantity)- Check if requested quantity availablegetItemValue()- Return price * stockQuantitytoString()- Return item details
OrderLine Requirements:
- Fields:
Item item,int quantity,double unitPrice - Constructor: Takes item and quantity, captures current price
- Methods:
getLineTotal()- Return quantity * unitPricegetItemName()- Return name from itemgetItemId()- Return ID from itemincreaseQuantity(int amount)- Add to quantitydecreaseQuantity(int amount)- Subtract from quantity (min 1)toString()- Return line item details
Order Requirements:
- Fields:
String orderId,String customerId,ArrayList<OrderLine> orderLines,String status,String orderDate - Constructor: Takes order ID, customer ID, and date
- Methods:
addOrderLine(OrderLine line)- Add line to orderremoveOrderLine(String itemId)- Remove line by item IDfindOrderLine(String itemId)- Return order line or nullgetOrderTotal()- Sum all line totalsgetItemCount()- Total quantity of all itemssetStatus(String status)- Update order statusgetOrderSummary()- Return formatted order detailshasItem(String itemId)- Check if order contains item
OrderManager Requirements:
- Fields:
ArrayList<Order> orders,HashMap<String, Item> inventory - Constructor: Initializes empty collections
- Methods:
addItem(Item item)- Add item to inventorycreateOrder(String orderId, String customerId)- Create new orderaddItemToOrder(String orderId, String itemId, int quantity)- Add item to existing orderprocessOrder(String orderId)- Validate stock and complete orderfindOrder(String orderId)- Return order or nullgetOrdersByCustomer(String customerId)- Return list of customer ordersgetTotalSales()- Sum value of all completed ordersgetInventoryValue()- Sum value of all items in stock
Classes: Author, Book, Member, Library
Create a comprehensive library system with complex object relationships.
Author Requirements:
- Fields:
String authorId,String name,String nationality,ArrayList<Book> books - Constructor: Takes author ID, name, and nationality
- Methods:
addBook(Book book)- Add book to author's collectiongetBookCount()- Return number of books by authorgetBookTitles()- Return ArrayList of book titleshasWrittenBook(String title)- Check if author wrote specific booktoString()- Return author info with book count
Book Requirements:
- Fields:
String isbn,String title,Author author,String genre,boolean isAvailable,Member borrowedBy - Constructor: Takes ISBN, title, author, and genre
- Methods:
borrowBook(Member member)- Set as borrowed if availablereturnBook()- Set as available, clear borrowergetBorrowedBy()- Return member who borrowed book or nullgetBookInfo()- Return comprehensive book informationisBorrowedBy(Member member)- Check if borrowed by specific membertoString()- Return book details with availability
Member Requirements:
- Fields:
String memberId,String name,String email,ArrayList<Book> borrowedBooks,int borrowLimit - Constructor: Takes member ID, name, email, and borrow limit
- Methods:
borrowBook(Book book)- Add book if under limit and book is availablereturnBook(Book book)- Remove book from borrowed listgetBorrowedCount()- Return number of currently borrowed bookscanBorrowMore()- Check if member can borrow additional booksgetBorrowedTitles()- Return ArrayList of borrowed book titleshasBook(String isbn)- Check if member has borrowed specific bookgetMemberSummary()- Return member info with borrowed books
Library Requirements:
- Fields:
String libraryName,ArrayList<Book> books,ArrayList<Member> members,ArrayList<Author> authors - Constructor: Takes library name
- Methods:
addBook(Book book)- Add book to library collectionaddMember(Member member)- Add member to libraryaddAuthor(Author author)- Add author to libraryfindBook(String isbn)- Return book or nullfindMember(String memberId)- Return member or nullsearchBooksByTitle(String title)- Return ArrayList of matching bookssearchBooksByAuthor(String authorName)- Return books by authorgetAvailableBooks()- Return list of books available for borrowingprocessBookReturn(String isbn)- Handle book return processgetLibraryStatistics()- Return comprehensive library stats
- Open the
topic.jshfile - Start with Exercise 1 (
AddressandPerson) - Pay attention to how objects reference other objects
- Test the relationships between nested objects
- Understand how changes in nested objects affect the containing object
- Progress through exercises, building more complex nested structures
- Object Composition: Objects containing other objects as fields
- Object References: Understanding how objects reference other objects
- Navigation: Accessing nested object properties and methods
- Lifecycle Management: Creating and managing related objects
- Bidirectional Relationships: Objects that reference each other
- Collection Management: Objects containing collections of other objects
- Clear Ownership: Understand which object "owns" which other objects
- Proper Encapsulation: Provide methods to access nested objects safely
- Consistency: Keep related objects in consistent states
- Null Safety: Handle cases where nested objects might be null
- Dependency Management: Understand how objects depend on each other
Each exercise has comprehensive tests that verify:
- Object creation and initialization
- Nested object navigation and access
- Collection management within objects
- Relationships between different objects
- Complex scenarios involving multiple nested objects
Focus on understanding how the objects work together as a system, not just individually!