Y
Yash Namdeo
Full-Stack Intern Lanos
Published 28 April 2026·50 min read
1000 OOP Assignments in Java
Metadata
| Field | Value |
|---|---|
| Topic | Object-Oriented Programming in Java |
| Total Questions | 1000 |
| Levels | Beginner, Intermediate, Advanced |
| Distribution | 300 Beginner, 300 Intermediate, 400 Advanced |
| Goal | Build deep practical OOP strength through disciplined problem solving |
| Note | Advanced questions are intentionally ordered from lower advanced difficulty to highest advanced difficulty |
How to Use This Sheet
- Solve Beginner in order if your base is weak.
- Solve Intermediate after you are comfortable with classes, objects, constructors, encapsulation, inheritance, abstraction, and interfaces.
- Solve Advanced strictly in order because the challenge is progressive.
- Write code by hand.
- Do not skip design questions. OOP skill is not only syntax.
Level 1: Beginner (300 Questions)
Classes, Objects, Fields, and Methods
- Create a
Studentclass withnameandagefields. - Create two objects of
Studentand print their values. - Add a method
introduce()inStudentthat prints student details. - Create a
Carclass withbrand,model, andspeed. - Write a method
showCarInfo()insideCar. - Create three
Carobjects with different values. - Create a
Bookclass withtitleandprice. - Write a method in
Bookthat prints whether the book is expensive ifprice > 500. - Create a
MobilePhoneclass withbrand,ram, andstorage. - Write a method to display all phone details.
- Create an
Employeeclass withid,name, andsalary. - Write a method to print yearly salary.
- Create a
Dogclass withnameandbreed. - Add a method
bark()that prints a sentence using the dog's name. - Create a
Movieclass withtitle,rating, andlanguage. - Add a method to print whether the movie is family-friendly if rating is less than 13.
- Create a
Laptopclass withbrand,price, andprocessor. - Add a method to compare if the laptop price is above a given amount.
- Create a
Rectangleclass withlengthandwidth. - Add methods
area()andperimeter(). - Create a
Circleclass withradius. - Add a method that returns the area of the circle.
- Create a
Fanclass withbrand,speedLevel, andisOn. - Add methods
turnOn()andturnOff(). - Create a
Penclass withcolorandprice. - Add a method to print whether the pen is premium if price is above 100.
- Create a
BankCustomerclass withcustomerIdandname. - Add a method to print a welcome message.
- Create a
Busclass withnumber,route, andseats. - Add a method to print whether seats are available if seats > 0.
- Create a
Shirtclass withsize,color, andprice. - Add a method that prints discount eligibility if price is above 1000.
- Create a
Speakerclass withbrand,volume, andisBluetooth. - Add a method to increase volume by 1.
- Create a
Keyboardclass withtype,isMechanical, andprice. - Add a method to print the keyboard category.
- Create a
Bottleclass withcapacityandmaterial. - Add a method to print if the bottle is travel-friendly if capacity <= 1 liter.
- Create a
Courseclass withcourseNameandduration. - Add a method to print course summary.
- Create a
Trainclass withtrainNumber,source, anddestination. - Add a method
printRoute(). - Create a
Songclass withtitle,artist, andduration. - Add a method to print whether the song is short if duration < 3 minutes.
- Create a
Watchclass withbrand,type, andprice. - Add a method to print whether the watch is digital or analog.
- Create a
Lightclass withisOnandwatt. - Add methods
switchOn()andswitchOff(). - Create a
Mouseclass withdpi,wireless, andbrand. - Add a method to print mouse category.
Constructors
- Create a
Studentclass with a default constructor. - Print a message from inside the default constructor of
Student. - Create a parameterized constructor for
Studentwithnameandage. - Create an object using the parameterized constructor and print values.
- Create a
Bookclass with both default and parameterized constructors. - Use constructor overloading in a
MobilePhoneclass. - Create a
Carconstructor that sets default speed to 0. - Create a
Rectangleconstructor that receives length and width. - Write a constructor that validates price cannot be negative.
- Create a
Fanconstructor that setsisOnto false by default. - Add a constructor to
Employeethat receives all fields. - Add a constructor to
Moviethat only receivestitle. - Add a constructor to
Moviethat receivestitleandrating. - Use
this()constructor chaining in aProductclass. - Create a
Laptopclass with three overloaded constructors. - Write a
BankAccountconstructor that sets balance to 0 if negative. - Create a
Courseconstructor that stores course name and duration. - Add constructor chaining to a
Circleclass. - Create a
Shirtclass with constructors for different levels of initialization. - Add a constructor to
Dogthat prints the breed during creation. - Create a
Penclass where price defaults to 10 if not passed. - Create a
Busclass with constructor overloading for local and express buses. - Create a
Speakerclass with one constructor for wired and one for wireless. - Create a
Bottleclass that uses constructor chaining. - Create a
Keyboardclass and initialize all fields using constructor. - Create a
Watchclass with a constructor that rejects negative price. - Write a
Lightconstructor that stores watt and default off state. - Create a
Mouseconstructor that takes only brand and defaults other fields. - Create a
Songconstructor that accepts title and artist only. - Create a
Trainconstructor that prints source and destination. - Create a
Studentconstructor that sets default grade toA. - Create an
Employeeconstructor that auto-initializes salary to 10000 if omitted. - Create a
Courseconstructor that validates duration > 0. - Create a
BankCustomerconstructor and print object state through a method. - Create a
Movieconstructor that rejects invalid rating. - Create a
Rectangleclass with constructor overloading for square and rectangle. - Create a
Circleconstructor that accepts integer radius and stores it as double. - Create a
Bookconstructor that sets title toUnknownwhen null. - Create a
Carconstructor that increments a static object counter. - Create a
Laptopconstructor that initializes an object and prints a success message. - Write a
Fanconstructor that validates speed level range. - Create a
Courseconstructor usingthisfor field assignment. - Create a
MobilePhoneconstructor using constructor chaining for common defaults. - Create a
Bottleconstructor that supports two capacities. - Create a
Busconstructor that sets seats to 40 if not passed. - Create a
Speakerclass where one constructor calls another with default volume. - Create an
Employeeconstructor that stores name in uppercase. - Create a
Studentconstructor that prevents negative age. - Create a
Trainconstructor that stores route code. - Create a
Watchconstructor that prints whether the object is premium during creation.
this, Instance State, and Validation
- Create a
Studentconstructor that usesthis.name = name. - Create a
Productclass where field and parameter names are same, then resolve usingthis. - Create a
Bookclass withthis()constructor chaining. - Create a
BankAccountclass withthis.balance. - Create a
CarmethodsetSpeed(int speed)and usethis.speed. - Create a
Laptopclass and returnthisfrom a method. - Create a
Rectangleclass with method chaining for setting length and width. - Create a
CirclemethodincreaseRadius(double value)and usethis. - Create a
Dogmethodrename(String name)usingthis. - Create a
MobilePhonemethod that returns current object after setting storage. - Create a
Fanmethod to set speed level and returnthis. - Create a
Watchmethod to update price only if positive. - Create a
Speakermethod to update volume only if between 0 and 100. - Create a
Studentmethod that prevents age from exceeding 100. - Create a
BankAccountmethoddeposit(double amount)with validation. - Create a
BankAccountmethodwithdraw(double amount)with validation. - Create a
Penmethod to update price only if positive. - Create a
Bottlemethod to update capacity only if valid. - Create an
Employeemethod to raise salary by a positive percentage. - Create a
Moviemethod to update rating only if between 0 and 10. - Create a
Busmethod to reserve one seat if available. - Create a
Trainmethod to change destination and returnthis. - Create a
Coursemethod to extend duration by a given number of days. - Create a
Keyboardmethod to mark keyboard as mechanical. - Create a
Mousemethod to change DPI safely. - Create a
Lightmethodtoggle()using current object state. - Create a
Songmethod to rename song usingthis. - Create a
Carmethod to accelerate by given amount. - Create a
Carmethod to brake without letting speed go below 0. - Create a
Studentmethod to print current object hash code. - Create a
Productmethod that compares price of current object with another product. - Create a
Rectanglemethod that compares area with another rectangle. - Create a
Circlemethod that returns true if current circle is larger than another. - Create a
Dogmethod that copies breed from another dog. - Create a
Bookmethod that copies price from another book. - Create a
Laptopmethod to upgrade RAM by given GB. - Create an
Employeemethod to reset salary to base value. - Create a
Speakermethod to mute and return current object. - Create a
Watchmethod that doubles price only if luxury flag is true. - Create a
MobilePhonemethod to combine storage upgrade and RAM upgrade. - Create a
Studentmethod to update both name and age. - Create a
Trainmethod to swap source and destination. - Create a
Bottlemethod to mark bottle as reusable. - Create a
Busmethod to refill seat count for next trip. - Create a
Moviemethod to reset rating. - Create a
Lightmethod that changes watt value only if above 0. - Create a
Penmethod that marks pen as out of stock. - Create a
Coursemethod to mark course completed. - Create a
BankCustomermethod to update mobile number with validation. - Create a
Keyboardmethod that returnsthisfor chained configuration.
Encapsulation and Access Modifiers
- Create a
BankAccountclass with privatebalance. - Add a public getter for
balance. - Add a public deposit method for
BankAccount. - Prevent direct access to
balancefrommain. - Create a
Userclass with privatepassword. - Add a setter that stores password only if length >= 8.
- Add a getter for username but not for password.
- Create an
Employeeclass with privatesalary. - Add a public method
showSalary()instead of direct getter. - Create a
Studentclass with privatemarks. - Add a method that updates marks only if between 0 and 100.
- Create a
Movieclass with privaterating. - Add getter and validated setter for rating.
- Create a
Carclass with privatespeed. - Add methods
accelerate()andbrake()instead of exposing speed setter. - Create a
Circleclass with privateradius. - Add a constructor and getter for radius.
- Prevent negative radius through constructor validation.
- Create a
Productclass with privateprice. - Add a method to apply percentage discount.
- Create a
Fanclass with privatespeedLevel. - Add methods to increase and decrease speed safely.
- Create a
BankCustomerclass with privatecustomerIdand no setter. - Explain in code why
customerIdshould not be changeable. - Create a
Lightclass with privateisOn. - Expose only
switchOn,switchOff, andisLightOn. - Create a
Bottleclass with privatecapacity. - Add a setter that accepts only positive values.
- Create a
Courseclass with privatecourseName. - Add public method to rename course if non-empty.
- Create a
Busclass with privateseats. - Add a method to decrement seat count when booking.
- Create a
Trainclass with privaterouteCode. - Add getter but no setter for route code.
- Create a
Watchclass with privateprice. - Add method to apply tax and return final price.
- Create a
Speakerclass with privatevolume. - Expose only safe methods for volume control.
- Create a
Laptopclass with privateram. - Add method
upgradeRam(int extra). - Create a
Mouseclass with privatedpi. - Add a getter and validated setter.
- Create a
Keyboardclass with privateisMechanical. - Add a getter named
isMechanical(). - Create a
Penclass with privatestock. - Add method to reduce stock on sale.
- Create a
Songclass with privateduration. - Add a getter and a method to extend duration for remix.
- Create a
Bookclass with privatetitle. - Add method to print uppercase title.
Static Members
- Create a
Carclass with static fieldtotalCars. - Increment
totalCarsevery time an object is created. - Print total objects created after making three
Carobjects. - Create a
Studentclass with static fieldschoolName. - Print the same
schoolNamefrom two student objects. - Change
schoolNameonce and show the effect on all objects. - Create a
Bookclass with static methodlibraryPolicy(). - Call static method using class name.
- Create an
Employeeclass with static fieldcompanyName. - Create a static method
changeCompanyName. - Create a
BankAccountclass with static interest rate. - Print simple interest using static rate and instance balance.
- Create a
Circleclass with static methodpiValue(). - Create a
Productclass with static tax rate. - Create a
Fanclass with static field counting running fans. - Increment and decrement static count when turning fan on or off.
- Create a
Trainclass with static fieldtransportType = "Rail". - Create a
Busclass with static fieldtransportType = "Road". - Create a
Laptopclass with static fieldwarrantyYears. - Update warranty years and show change across objects.
- Create a
Speakerclass with static constantMAX_VOLUME. - Use
MAX_VOLUMEin volume validation. - Create a
Watchclass with static fieldbrandCount. - Create a static method to print number of created watches.
- Create a
Mouseclass with static utility methodisGamingDpi(int dpi). - Create a
Keyboardclass with static method to compare two prices. - Create a
Bottleclass with static method converting liters to milliliters. - Create a
Courseclass with static fieldplatformName. - Create a
Movieclass with static method to validate rating. - Create a
Penclass with static fieldmanufacturer. - Create a
Songclass with static method to convert minutes to seconds. - Create a
Studentclass with both static and instance fields and print both. - Create an
Employeeclass with static initialization of company policy text. - Create a
BankCustomerclass with static method to validate phone number length. - Create a
Carclass with static methodcompareBrands(Car a, Car b). - Create a
Busclass with static fare rate per km. - Create a
Trainclass with static field for current fiscal year. - Create a
Courseclass with static counter for total enrollments. - Create a
Bookclass with static discount rate for all books. - Create a
Laptopclass with static method to print common configuration tips. - Create a
MobilePhoneclass with static method to format IMEI. - Create a
Circleclass with static method to create a unit circle. - Create a
Rectangleclass with static helper to make square. - Create a
Fanclass with static method to validate speed level. - Create a
Lightclass with static unit conversion for watts to kilowatts. - Create a
Speakerclass with static method to test if volume is safe. - Create a
Watchclass with static method to compare two models. - Create a
Mouseclass with static field for default DPI. - Create a
Keyboardclass with static field for default key count. - Create a
Penclass with static factory-like method returning a blue pen.
Inheritance Basics
- Create a parent class
Animaland child classDog. - Add
eat()inAnimalandbark()inDog. - Create an object of
Dogand call both methods. - Create parent
Vehicleand childCar. - Add
start()inVehicleandopenTrunk()inCar. - Create parent
Personand childStudent. - Add common fields in
Personand student-specific field inStudent. - Create parent
Employeeand childManager. - Add common method
work()inEmployee. - Add specific method
conductMeeting()inManager. - Create parent
Shapeand childRectangle. - Add parent
displayType()and child-specificarea(). - Create parent
Applianceand childFan. - Add
turnOn()in parent andchangeSpeed()in child. - Create parent
Accountand childSavingsAccount. - Add balance field in parent and
interestRatein child. - Create parent
Bookand childTextBook. - Add subject field in child.
- Create parent
Mobileand childSmartPhone. - Add internet-specific method in child.
- Create parent
Employeeand childDeveloper. - Add coding hours field in
Developer. - Create parent
Furnitureand childChair. - Add fold feature in child.
- Create parent
Machineand childPrinter. - Add
printDocument()in child. - Create parent
Paymentand childCardPayment. - Add parent field
amountand child fieldcardNumber. - Create parent
Animaland childCat. - Add
meow()in child. - Create parent
Deviceand childLaptop. - Add
compileCode()in child. - Create parent
Shapeand childCircle. - Create parent
Userand childAdmin. - Add
manageUsers()inAdmin. - Create parent
Transportand childBus. - Add
openDoor()in child. - Create parent
Workerand childTeacher. - Add
teach()in child. - Create parent
Accountand childCurrentAccount. - Add transaction charge field in child.
- Create parent
Mediaand childSong. - Add singer field in child.
- Create parent
Courseand childProgrammingCourse. - Add language field in child.
- Create parent
Gameand childChess. - Add
movePiece()in child. - Create parent
Buildingand childSchool. - Add
conductAssembly()in child. - Create parent
FoodItemand childPizza.
Level 2: Intermediate (300 Questions)
Inheritance, super, Overriding, and Runtime Behavior
- Create
AnimalandDog, then usesuperto initialize parent fields. - Create
VehicleandCar, then call parent constructor withsuper. - Override a method
sound()in child classDog. - Override a method
start()in child classCar. - Create
EmployeeandDeveloper, overridecalculateSalary(). - Create
Shapehierarchy and overridearea()in each child. - Create
AccountandSavingsAccount, overrideshowAccountType(). - Create
BookandTextBook, overridedisplayInfo(). - Create
PaymentandCardPayment, overrideprocess(). - Create
MobileandSmartPhone, overrideshowSpecs(). - Create
MediaandSong, overrideplay(). - Create
FurnitureandChair, overrideshowMaterial(). - Create
GameandChess, overridestartGame(). - Create
ApplianceandFan, overridepowerConsumption(). - Create
WorkerandTeacher, overridework(). - Create
UserandAdmin, overridelogin(). - Create
TransportandBus, overrideshowFare(). - Create
CourseandProgrammingCourse, overrideshowSyllabus(). - Create
BuildingandSchool, overrideshowPurpose(). - Create
FoodItemandPizza, overrideprepare(). - Create parent
Messageand childEmailMessage, overridesend(). - Create parent
Discountand childFestivalDiscount, overrideapply(). - Create parent
Sensorand childTemperatureSensor, overridereadValue(). - Create parent
Reportand childPdfReport, overridegenerate(). - Create parent
Playerand childCricketPlayer, overrideplay(). - Create parent
Subscriptionand childPremiumSubscription, overrideprice(). - Create parent
Questionand childMCQQuestion, overridedisplay(). - Create parent
Roomand childClassRoom, overrideshowUsage(). - Create parent
HospitalStaffand childDoctor, overrideperformDuty(). - Create parent
Machineand childWashingMachine, overrideoperate(). - Create
Animal a = new Dog()and call overridden method. - Create
Vehicle v = new Car()and call overriddenstart(). - Store a
Developerobject inEmployeereference and callcalculateSalary(). - Demonstrate runtime polymorphism using
Shapearray. - Demonstrate runtime polymorphism using
Paymentarray. - Create a loop over
Animal[]containingDogandCatobjects. - Show that fields are not polymorphic but methods are.
- Override method and call parent version using
super.methodName(). - Create child method that extends parent behavior instead of replacing it completely.
- Override
toString()in a child class.
Encapsulation, Class Design, and Validation
- Design a
BankAccountwith private state and strict withdraw validation. - Design a
Studentclass where marks update must stay within 0 to 100. - Design a
Productclass where price cannot be negative. - Design an
Employeeclass where ID is immutable after object creation. - Design a
Movieclass where rating can change but title cannot. - Design a
Rectangleclass where dimensions must always remain positive. - Design a
Circleclass with controlled radius growth only. - Design a
Userclass where password is write-only and validated. - Design a
Courseclass where completed course cannot reduce duration. - Design a
Busclass where booked seats cannot exceed total seats. - Design a
TrainTicketclass where cancellation is blocked after travel date. - Design a
Laptopclass where RAM can only be upgraded, not downgraded. - Design a
MobilePhoneclass where IMEI cannot change after construction. - Design a
Bookclass where ISBN is read-only. - Design a
Speakerclass where volume range is 0 to 100. - Design a
Watchclass where price update logs old and new values. - Design a
Mouseclass with validated DPI range. - Design a
Keyboardclass where key count cannot be less than 60. - Design a
Penclass with stock that cannot go below zero. - Design a
Bottleclass where capacity must be in milliliters and positive. - Design an
Orderclass with private status and controlled transitions. - Design a
Taskclass with restricted priority values. - Design an
Invoiceclass with immutable invoice number. - Design a
Customerclass with controlled email updates. - Design a
Flightclass where seats and fare are validated. - Design a
LibraryMemberclass where membership status is internally controlled. - Design a
Reservationclass where confirmation only happens once. - Design a
Walletclass with deposit and spend rules. - Design a
Quizclass where marks are recalculated through methods only. - Design a
Loanclass where interest cannot be negative.
Abstract Classes and Interfaces
- Create an abstract class
Shapewith abstract methodarea(). - Implement
CircleandRectangleusing abstractShape. - Create an abstract class
Paymentwith abstractprocessPayment(). - Implement
CardPaymentandUpiPaymentfromPayment. - Create an interface
NotificationSenderwith methodsend. - Implement
EmailSenderandSmsSender. - Create an interface
Playableand implement it inSong. - Create an interface
Flyableand implement it inBird. - Create an abstract class
Employeeand deriveDeveloperandManager. - Create abstract class
Appliancewith common fieldbrand. - Implement
FanandWashingMachinefrom abstractAppliance. - Create an interface
DiscountStrategywithapplyDiscount. - Implement
NoDiscount,StudentDiscount, andFestivalDiscount. - Create an abstract class
Reportwith methodgenerate. - Implement
PdfReportandExcelReport. - Create an interface
Loggerand implementConsoleLogger. - Implement
FileLoggerfor sameLoggerinterface. - Create an abstract class
Vehiclewith abstractfuelType. - Implement
PetrolCarandElectricCar. - Create an interface
Searchableand implement it inBookCatalog. - Create an abstract class
Accountwith abstractcalculateInterest. - Implement
SavingsAccountandFixedDepositAccount. - Create an interface
Taxableand implement it inProduct. - Create an abstract class
GameCharacterwith abstractattack. - Implement
WarriorandMage. - Create an interface
Exportableand implement inCsvExporter. - Implement
JsonExporterfor sameExportableinterface. - Create an abstract class
Messagewith concretevalidateRecipient. - Implement
EmailMessageandSmsMessage. - Create an interface
AuthenticationProviderand implement two providers. - Create abstract class
ExamQuestionand subclasses for text and code questions. - Create an interface
Cacheand implementMemoryCache. - Create
RedisCacheclass for sameCacheinterface. - Create abstract class
Notificationwith abstractdeliver. - Create interface
Payableand make multiple unrelated classes implement it. - Create a class implementing two interfaces.
- Create an interface with default method and override it in implementation.
- Create an interface with static utility method and call it via interface name.
- Compare abstract class and interface in one mini-system.
- Create a
Deviceabstraction and model behavior using both abstract class and interface.
Composition and Object Collaboration
- Create a
Carclass that contains anEngineobject. - Create a
Computerclass that containsKeyboardandMonitor. - Create a
Libraryclass that contains multipleBookobjects. - Create a
Schoolclass that contains multipleStudentobjects. - Create an
Orderclass that contains multipleProductobjects. - Create a
Playlistclass that contains multipleSongobjects. - Create a
Teamclass that contains multiplePlayerobjects. - Create a
Walletclass that contains multipleTransactionobjects. - Create a
Courseclass that contains multipleLessonobjects. - Create a
Hospitalclass that contains multipleDoctorobjects. - Create a
Departmentclass that holds employees and prints headcount. - Create a
Companyclass containing departments and employees. - Create a
Cartclass with methods to add and remove products. - Create a
ReportServicethat uses aLogger. - Create an
OrderServicethat uses aNotificationSender. - Create a
PaymentServicethat uses aPaymentGateway. - Create a
StudentServicethat uses aStudentRepository. - Create a
TicketServicethat uses aPricingStrategy. - Create a
VideoPlayerthat uses aSubtitleRenderer. - Create a
RestaurantOrderthat uses aBillCalculator. - Create a
UserProfilethat contains anAddressvalue object. - Create a
TravelPlanthat contains multipleCityStopobjects. - Create a
ChessGameclass that containsBoardandPlayerobjects. - Create a
CabTripthat containsDriver,Rider, andFarePolicy. - Create a
FoodDeliveryOrderthat uses aDeliveryPartner. - Create a
BlogPostthat contains multipleCommentobjects. - Create a
ChatRoomthat contains manyMessageobjects. - Create a
MovieTicketBookingthat usesSeatAllocator. - Create a
ParkingLotthat containsParkingSlotobjects. - Create a
Bankclass that manages manyBankAccountobjects.
Method Overloading, Overriding, and Object Utility Methods
- Overload
add()for two integers and three integers. - Overload
add()forintanddouble. - Overload
printDetails()with different parameters. - Overload
calculateArea()for square and rectangle. - Overload
login()with username-password and mobile-OTP. - Overload
setData()for different field combinations. - Overload constructor and also overload a behavior method in same class.
- Override
toString()inStudent. - Override
equals()inStudentbased on ID. - Override
hashCode()consistently withequals(). - Override
toString()inProductand print object directly. - Override
equals()inBookbased on ISBN. - Override
toString()inBankAccount. - Override
toString()inEmployeehierarchy and print polymorphically. - Override a method and call
superbefore child logic. - Override a method and call
superafter child logic. - Create overloaded
pay()methods with different signatures. - Create overloaded
search()methods for id and name. - Create overloaded
notifyUser()methods for email and SMS text. - Create overloaded
bookSeat()methods for one seat and many seats. - Create overloaded
deposit()methods for int and double. - Create overloaded
withdraw()methods with and without remarks. - Create a class where overloading would cause ambiguity and resolve it.
- Show invalid overloading by changing only return type and explain why.
- Create parent-child classes and override
display()correctly. - Create parent-child classes and intentionally break override using different parameters.
- Use
@Overrideannotation to catch override mistakes. - Create a class with overloaded
build()methods returning different configured objects. - Create a child class that overrides
calculate()and narrows behavior correctly. - Create utility class demonstrating
toString,equals, andhashCodetogether.
Scenario-Based Intermediate Assignments
- Design a
LibraryBooksystem with borrow and return methods. - Design a
BusPasssystem with validity and renewal behavior. - Design a
StudentReportCardwith subject marks and grade methods. - Design a
FoodOrderwith item count and billing logic. - Design a
ShoppingCartwith add, remove, and total methods. - Design an
ATMmodel with withdraw, deposit, and balance inquiry. - Design a
MovieBookingobject with seat confirmation logic. - Design a
FlightTicketmodel with cancel and reschedule rules. - Design a
HotelRoombooking model with availability updates. - Design a
GymMembershipclass with active and expired states. - Design a
VehicleInsuranceclass with premium calculation. - Design a
LoanApplicationclass with approval eligibility logic. - Design a
QuizAppQuestionhierarchy with text and MCQ questions. - Design a
RestaurantTableBookingclass with reservation status changes. - Design a
CourierPackageclass with tracking status and fee. - Design a
RideBookingmodel with fare and trip status. - Design a
CinemaSeatclass with lock and book actions. - Design a
WarehouseItemwith stock and reorder threshold. - Design a
LibraryMemberclass with fine calculation. - Design an
ECommerceProductReviewclass with rating validation. - Design a
ClassroomAttendanceclass with present and absent counters. - Design a
TournamentTeamclass with wins, losses, and points. - Design a
MusicPlaylistclass with play next and remove song behavior. - Design a
TaskManagerItemwith state transitions. - Design a
PrinterQueueJobmodel with queued, printing, and done states. - Design a
TrainReservationclass with RAC and waiting list states. - Design an
InventoryMovementclass with incoming and outgoing stock. - Design a
FoodCouponsystem using discount strategy objects. - Design a
DocumentApprovalworkflow using status checks. - Design a
CustomerSupportTicketwith escalation behavior. - Design a
BlogPostandCommentmodel with ownership rules. - Design a
ParkingTicketsystem with time-based billing. - Design a
CabDriverpayout model with per-trip earnings. - Design a
Medicineclass with expiry-date validation. - Design a
HospitalAppointmentclass with scheduling logic. - Design a
MealPlanclass with calorie calculations. - Design a
ShoppingCouponhierarchy with fixed and percentage discounts. - Design a
NotificationCenterthat supports multiple senders. - Design a
UserSessionclass with login, logout, and timeout. - Design a
TaxCalculatorstrategy-based system.
Mini Projects and Refactoring Questions
- Refactor a student record program with raw variables into a
Studentclass. - Refactor a product billing program into
ProductandBillclasses. - Refactor a banking script into encapsulated
BankAccount. - Refactor a marks calculator into
Student,Subject, andReportCard. - Refactor a ticket booking script using classes and methods.
- Refactor a restaurant bill calculator using object collaboration.
- Refactor a print-all-in-main program into multiple classes.
- Refactor a repeated-discount code block into discount strategy classes.
- Refactor a large
if-elsepayment selection into polymorphism. - Refactor duplicated
DogandCatcode into inheritance. - Refactor a
Vehiclehierarchy that wrongly duplicates speed code. - Refactor a public-field
Employeedesign into encapsulated design. - Refactor a class with too many setters into safer design.
- Refactor a class with mixed responsibilities into two cohesive classes.
- Refactor a
GodServicethat handles orders, payment, and notifications. - Refactor a loyalty discount logic into an interface-based solution.
- Refactor a file export utility into separate exporter classes.
- Refactor a system that uses
instanceofeverywhere into polymorphism. - Refactor an immutable value object that currently has setters.
- Refactor an inheritance design that should really use composition.
- Refactor a chat app model where message sending is hardcoded.
- Refactor a report generator to support PDF and CSV exporters.
- Refactor a login system to support multiple authentication providers.
- Refactor a direct-email dependency into interface-based notification.
- Refactor a shopping cart to use
CartItemobjects instead of parallel arrays. - Refactor an exam system where all question types live in one huge class.
- Refactor a game character class into parent and specialized child classes.
- Refactor a device system to avoid repeated validation logic.
- Refactor an invoice model to introduce a value object for money.
- Refactor a library management model to protect book status changes.
Progressive Intermediate Challenge Set
- Build a
LibrarySystemwith books, members, and issue logic. - Extend the
LibrarySystemwith fine calculation. - Extend the
LibrarySystemwith separate item types: book, magazine, journal. - Build an
OrderSystemwith products and order total. - Extend the
OrderSystemwith discount strategies. - Extend the
OrderSystemwith notification sending. - Build an
EmployeePayrollhierarchy with salary overrides. - Extend
EmployeePayrollwith bonus policies. - Extend
EmployeePayrollwith tax calculation abstraction. - Build a
ParkingLotwith slots and parked vehicles. - Extend
ParkingLotwith different vehicle types. - Extend
ParkingLotwith ticket calculation rules. - Build a
QuizSystemwith multiple question types. - Extend
QuizSystemwith scoring strategies. - Extend
QuizSystemwith report export support. - Build a
FoodDeliverymodel with restaurant, menu item, and order. - Extend
FoodDeliverywith coupon strategy support. - Extend
FoodDeliverywith delivery-partner assignment. - Build a
HospitalManagementmini-model with doctor, patient, appointment. - Extend it with billing logic.
- Extend it with notification reminders.
- Build a
RideBookingmodel with rider, driver, and trip. - Extend it with fare strategies.
- Extend it with trip cancellation policies.
- Build a
SchoolSystemwith student, teacher, classroom. - Extend it with attendance tracking.
- Extend it with exam result generation.
- Build a
MovieBookingSystemwith seat, screen, show. - Extend it with payment abstraction.
- Extend it with ticket cancellation rules.
- Build a
WarehouseSystemwith items and stock changes. - Extend it with supplier tracking.
- Extend it with reorder alert logic.
- Build a
GymManagementsystem with member, plan, trainer. - Extend it with attendance log objects.
- Extend it with plan-upgrade rules.
- Build a
MusicAppmodel with playlist and song objects. - Extend it with shuffle logic.
- Extend it with favorite song tracking.
- Build an
ATMSystemwith account operations and transaction history. - Extend it with transaction type hierarchy.
- Extend it with receipt generation.
- Build an
InsurancePolicymodel. - Extend it with policy type hierarchy.
- Extend it with claim processing abstraction.
- Build a
TravelBookingmodel with traveler, ticket, hotel. - Extend it with cancellation rules.
- Extend it with invoice generation.
- Build an
ECommerceReviewsystem. - Extend it with moderation workflow.
- Extend it with report abuse behavior.
- Build a
DocumentWorkflowmodel. - Extend it with approval roles.
- Extend it with notification channels.
- Build a
CabFleetsystem with vehicles and availability. - Extend it with driver rating logic.
- Extend it with maintenance status support.
- Build a
RestaurantBillingsystem. - Extend it with tax and discount policies.
- Extend it with multiple payment modes.
Level 3: Advanced (400 Questions)
Important Note for Advanced Level
Questions 601 to 1000 are intentionally ordered from lower advanced difficulty to highest advanced difficulty. Do not solve them randomly if your goal is real growth.
Advanced Stage 1: Strong OOP Implementation and Design Reasoning (601-700)
- Design a
Moneyvalue object that is immutable and supports safe addition only for same currency. - Add subtraction support to
Moneywhile preventing negative results when business rule disallows it. - Add comparison methods to
Moneyand define logical equality correctly. - Override
equals,hashCode, andtoStringforMoney. - Design an immutable
EmailAddressvalue object that validates format at construction time. - Design an immutable
DateRangeobject that rejects invalid start-end order. - Add overlap detection to
DateRange. - Add containment checks to
DateRange. - Design a
Percentagevalue object that only allows 0 to 100. - Use
Percentageinside a discount system instead of raw doubles. - Design a
UserIdvalue object and replace rawStringIDs in a user model. - Design an immutable
Addressobject and embed it insideCustomer. - Design a mutable
ShoppingCartthat only accepts validCartItemobjects. - Prevent duplicate product entries in
ShoppingCartby merging quantities. - Add total price calculation to
ShoppingCart. - Add remove and decrement behaviors to
ShoppingCart. - Introduce a
PricingPolicyabstraction intoShoppingCart. - Add coupon application without modifying core cart logic directly.
- Design
CartItemso quantity can never become zero or negative. - Design a
ProductCatalogclass that exposes safe lookup operations but not internal storage directly. - Design a
StudentRegistrythat prevents duplicate roll numbers. - Add update behavior to
StudentRegistrywithout exposing raw collection state. - Design an
ExamResultobject that computes grade lazily or eagerly and justify your choice. - Design a
TransactionHistoryclass that records deposits and withdrawals as separate objects. - Add a rule that every transaction must carry timestamp and type.
- Design a
BankStatementreport object fromTransactionHistory. - Separate bank domain entities from report-generation concerns.
- Design a
PasswordPolicyabstraction and inject it intoUserRegistrationService. - Implement two password policies and switch them without changing registration flow.
- Design a
LoginAttemptTrackerwith locked-state rules. - Prevent state corruption in
LoginAttemptTrackerunder repeated failed attempts. - Design a
CourseEnrollmentobject linking student and course with enrollment status. - Add state transitions such as enrolled, completed, dropped, and rejected.
- Ensure invalid transitions are blocked.
- Design a
RoomBookingmodel that rejects overlapping bookings. - Separate booking validation from persistence concerns.
- Design a
SeatAllocatorabstraction for theater booking. - Implement two seat-allocation strategies and switch them polymorphically.
- Design a
TaxPolicyabstraction for products of different categories. - Add country-specific tax calculation without rewriting product model.
- Design a
ShippingChargePolicyabstraction. - Combine
TaxPolicyandShippingChargePolicyin a checkout flow. - Design a
Billobject that keeps line items immutable after generation. - Prevent recalculation bugs by freezing bill totals after confirmation.
- Design a
RefundRequestlifecycle model. - Add approval and rejection transitions to
RefundRequest. - Design a
SupportTicketmodel that tracks assignment and escalation cleanly. - Add comments to
SupportTicketusing composition. - Separate comment author identity from comment content through value objects.
- Design a
RideFareCalculatorabstraction with multiple pricing modes. - Add surge pricing without modifying core ride entity.
- Add coupon support on top of fare calculation.
- Design a
SubscriptionPlanhierarchy and explain where inheritance is justified. - Replace an incorrect
SubscriptionPlaninheritance design with composition. - Design a
NotificationTemplatesystem with different renderers. - Create renderer abstraction for email, SMS, and push formatting.
- Prevent channel-specific logic from leaking into template model.
- Design a
PaymentReceiptobject with immutable state. - Add a
ReceiptFormatterabstraction and multiple implementations. - Design an
AuditLogclass that is append-only. - Prevent edits to historical log entries.
- Design a
FeatureFlagobject that supports controlled evaluation. - Separate flag evaluation rules from flag storage.
- Design a
LibraryLoanobject that tracks due date and renewal rules. - Prevent renewal after max renewal count.
- Design a
PenaltyPolicyabstraction for overdue items. - Add different penalties for book, DVD, and journal loans.
- Design a
VehicleAssignmentmodel linking driver and cab. - Prevent assigning one active cab to multiple drivers at once.
- Design a
BatchProcessorthat applies a common interface to many tasks. - Add result aggregation while keeping task interface small.
- Design an
ImportJobstate machine with pending, running, failed, completed. - Prevent illegal state transitions in
ImportJob. - Design a
DocumentVersionmodel with immutable revisions. - Add a
Documentaggregate that owns versions safely. - Design a
Leaderboardobject that maintains top scores. - Prevent direct score tampering by exposing only update methods.
- Design a
StudentAttendancePolicyabstraction. - Implement strict and relaxed attendance policies.
- Design a
FeeCalculatorusing strategy objects. - Add scholarship policy composition to
FeeCalculator. - Design a
PromoCodedomain model with expiration and usage rules. - Prevent reusing single-use promo codes.
- Design a
ParkingSessionwith entry time, exit time, and fee calculation. - Separate fee calculation from parking session entity.
- Design a
ReservationStatusmodel that avoids stringly typed code. - Replace raw status strings with enum-based or object-based modeling.
- Design a
QuestionBankclass that groups question objects by topic. - Add polymorphic question evaluation without giant
if-elsechains. - Design a
ChatMessagehierarchy and justify what should be common parent state. - Prevent a
ChatRoomfrom exposing internal mutable message storage. - Design an
InvoiceNumberGeneratorwith uniqueness guarantee at object level. - Separate identifier generation from invoice behavior.
- Design an
InventoryReservationobject. - Prevent selling inventory already reserved by another order.
- Design a
GradePolicyabstraction. - Implement grade calculation by marks, percentile, and relative ranking.
- Design a
TranslationServiceabstraction with swappable providers. - Build a small cohesive model around
Order,OrderLine, andMoney. - Refactor that small order model to improve immutability and responsibility boundaries.
Advanced Stage 2: Polymorphism, Interfaces, and Behavior-Centric Design (701-800)
- Design a report-export system where adding a new format requires zero changes to existing exporters.
- Add PDF, CSV, and JSON exporters using interface-based design.
- Introduce a common export coordinator that depends only on abstraction.
- Design a command-processing system where each command is its own object.
- Add undo capability to the command system.
- Separate command validation from command execution.
- Design a payment processing pipeline with validation, execution, and notification stages.
- Keep the pipeline open for new payment methods without modifying coordinator logic.
- Model a
RuleEnginewhere each rule can approve or reject an input object. - Add rule composition using AND and OR combinations.
- Design a
PricingEnginewhere pricing rules are pluggable. - Add customer-tier pricing, coupon pricing, and seasonal pricing together.
- Resolve rule ordering problems without hardcoded
if-elsechains. - Design a
SearchFilterabstraction for product filtering. - Add category, price-range, and rating filters.
- Allow combining filters dynamically.
- Design a
Serializerinterface with implementations for XML, JSON, and plain text. - Introduce a service that works with any
Serializer. - Design a
StorageServiceabstraction for local, cloud, and in-memory storage. - Ensure calling code does not know storage implementation details.
- Design a
NotificationChannelhierarchy and add retry rules. - Separate message formatting from message sending.
- Design a game skill system using object hierarchies or interfaces.
- Add cooldown behavior without tightly coupling skill logic to player logic.
- Introduce effect stacking rules through composition.
- Design a discount engine that supports chained discounts with clear rules.
- Prevent invalid discount combinations through policy objects.
- Design an achievement system where each achievement is evaluated independently.
- Add polymorphic conditions for time-based and event-based achievements.
- Design a
WorkflowStepabstraction for approval flows. - Create multiple steps and a coordinator that only depends on the step contract.
- Add rollback or compensation behavior to failed workflow steps.
- Design a
ReportSchedulerthat runs different report tasks polymorphically. - Add result notification without mixing scheduler and notifier responsibilities.
- Design an
AuthenticationFlowwhere multiple strategies exist for login. - Add password login, OTP login, and OAuth-style placeholder login.
- Ensure controller logic depends on abstraction only.
- Design a
FraudCheckpipeline for transactions. - Add velocity, amount, and device-based checks as interchangeable rules.
- Design a classroom evaluation system where question type drives grading behavior.
- Avoid type checking in grading logic.
- Design a tax engine with composable policies and exemption rules.
- Add a country-specific adapter layer without breaking existing tax abstractions.
- Design a
DocumentParserinterface and create multiple parser implementations. - Add a coordinator that chooses parser based on document type cleanly.
- Design a file-upload validation system using rule abstractions.
- Add size, type, and virus-scan rules without giant controller logic.
- Design a workflow where
OrderServicedepends onInventoryChecker,PaymentProcessor, andNotifier. - Replace direct concrete dependencies with abstractions.
- Demonstrate how test doubles become easier with this design.
- Design an event-listener style interface for user actions.
- Add multiple listeners without changing source event producer.
- Design a
PromotionEligibilitysystem. - Add employee-based, purchase-count-based, and referral-based eligibility rules.
- Design a
RecommendationStrategyabstraction. - Add popular-item, recent-item, and similarity-based dummy strategies.
- Design a
QuestionEvaluationStrategyabstraction for coding platform questions. - Separate code execution result parsing from final score calculation.
- Design a
CachePolicyabstraction with eviction strategies. - Add LRU-like placeholder and no-eviction strategy behaviorally.
- Design a booking confirmation system with channel-specific confirmation senders.
- Ensure new channels do not require editing booking logic.
- Design a mini game engine loop that calls polymorphic
update()on entities. - Add player, enemy, and projectile entities without type checks.
- Design a stateful
MediaPlayermodel and then refactor it into state-like behavior objects. - Design a
PaymentFailureHandlerabstraction. - Add different failure responses based on failure type.
- Design a scheduler with task priorities using behavior-rich task objects.
- Add logging decorators around task execution.
- Design a
DocumentFormatterabstraction for resume generation. - Add section-level formatters through composition.
- Design a
ShippingProviderabstraction with cost and ETA methods. - Add two providers and a service that compares them.
- Design a
RideMatchingStrategyabstraction. - Add nearest-driver and least-busy-driver strategies.
- Design a
DeliverySlotAllocatorabstraction. - Add different slot-selection policies.
- Design a fraud alert notification design using abstraction, composition, and strategy.
- Build a reusable policy-driven validation framework using interfaces.
- Add short-circuit evaluation rules to that framework.
- Design a
DocumentSignerabstraction. - Add manual and auto-sign signer implementations.
- Build a
FormFieldValidatorframework with one validator per rule. - Add aggregation of errors without hardwiring validation logic.
- Design a
SurveyQuestionhierarchy with rendering and answer validation. - Add text, MCQ, checkbox, and rating questions.
- Build a polymorphic
Shapeeditor that can draw and resize objects withoutinstanceof. - Extend it with grouping behavior while keeping responsibilities clear.
- Design a
TravelFareStrategysystem that supports train, bus, cab, and flight placeholders. - Ensure route planner depends on abstraction only.
- Design a
RuleBasedMessageRouterusing condition and handler abstractions. - Add route branching without nested conditional complexity.
- Design a
DeviceHealthChecksystem with pluggable checks. - Add CPU, memory, disk, and network checks.
- Design a
TransactionProcessorwith pluggable steps and handlers. - Make it testable without real gateway or notifier.
- Design an interview-grade
ParkingLotabstraction for vehicle type pricing. - Add polymorphic parking fee calculation and slot assignment.
- Refactor a large billing
if-elseinto strategy and policy objects. - Refactor a role-based access check into capability-based abstractions.
Advanced Stage 3: Composition, Aggregates, State, and Robust Domain Modeling (801-900)
- Design an
Orderaggregate root that ownsOrderLineobjects and protects invariants. - Prevent
OrderLinefrom existing in invalid quantity state. - Prevent confirmed orders from being edited directly.
- Add explicit methods for adding, removing, and changing quantity safely.
- Design an
Invoiceaggregate with immutable line snapshots fromOrder. - Explain why invoice should not hold mutable references back to live order lines.
- Design a
Libraryaggregate withMember,BookCopy, andLoan. - Protect the rule that one book copy cannot be loaned twice at the same time.
- Add waiting-list behavior without corrupting loan rules.
- Design a
Tripaggregate with driver, rider, and fare breakdown. - Prevent invalid trip status transitions.
- Add cancellation rules depending on trip stage.
- Design a
SeatMapobject that owns seat state transitions. - Prevent double booking under repeated requests in the domain model.
- Model a school exam aggregate with exam, sections, and questions.
- Prevent score updates after publishing results.
- Design a
ShoppingCarttoOrderconversion flow as a domain transition. - Ensure cart mutability and order immutability are properly separated.
- Design a
Warehouseaggregate with stock lots instead of raw counts. - Prevent shipping more items than available across lots.
- Design a
PayrollRunobject that owns employee salary calculations for a pay cycle. - Prevent recalculating archived payroll runs accidentally.
- Design a
Projectaggregate with tasks, assignees, and status rules. - Ensure a project cannot be marked complete while active tasks remain incomplete.
- Design a
BlogPostaggregate with comments and moderation actions. - Prevent deleted posts from accepting new comments.
- Design a
CartPromotionApplicationobject that records which promotions were used. - Prevent stacking incompatible promotions.
- Design a
Reservationaggregate for restaurant booking with table assignment. - Prevent assigning two reservations to one table for overlapping times.
- Design a
LoanRepaymentScheduleobject. - Protect repayment ordering rules and overdue calculations.
- Design a
HospitalVisitaggregate with patient, doctor notes, prescription, and billing. - Ensure closed visits cannot be modified except through explicit amendment flow.
- Design a
TicketConversationmodel with comment timeline and status changes. - Separate public replies and internal notes cleanly.
- Design a
ContestSubmissionmodel with attempt history. - Prevent hidden mutation of historical attempts.
- Design a
GradeBookaggregate with student records and locked terms. - Ensure published term results cannot be changed without revision workflow.
- Design a
HotelStaymodel with check-in, extension, and check-out rules. - Prevent room reassignment after checkout completion.
- Design a
FoodOrderaggregate with line items, kitchen status, and billing status. - Ensure kitchen-prepared items cannot be silently removed.
- Design a
SubscriptionAccountmodel with renew, suspend, cancel, and resume transitions. - Prevent invalid state transitions.
- Design a
ParcelShipmentaggregate with checkpoints and delivery status. - Prevent delivered parcels from re-entering in-transit state.
- Design a
RecruitmentPipelinemodel with candidates and interview stages. - Ensure rejected candidates cannot move to later interview rounds directly.
- Design a
ClassSessionaggregate with attendance, topic coverage, and homework. - Prevent attendance changes after session lock unless admin amendment exists.
- Design a
PaymentAttempthistory model for an order. - Separate order payment status from individual payment attempts.
- Design a
Budgetaggregate with categories and allocations. - Prevent overspending relative to category allocation unless override policy exists.
- Design a
WarehouseTransferobject moving stock between locations. - Prevent transfer completion without source deduction and destination addition both succeeding.
- Design a
ReturnRequestaggregate that owns item-level return reasons. - Prevent approving return quantities greater than purchased quantities.
- Design a
DriverShiftmodel with start, end, breaks, and active-trip rules. - Prevent shift closure while an active trip exists.
- Design a
FoodDeliveryBatchmodel grouping multiple deliveries. - Ensure batch status reflects child delivery statuses coherently.
- Design a
MedicalPrescriptionaggregate with medicine lines and dosage rules. - Prevent editing dosage after doctor approval without amendment note.
- Design an
ExamPapermodel with section ordering and total marks validation. - Prevent total marks mismatch from final publication.
- Design a
Playlistmodel where position ordering is explicit. - Prevent inconsistent ordering after song insertions and removals.
- Design a
ResearchSubmissionworkflow with draft, submitted, reviewed, accepted, rejected. - Encode valid transitions without stringly typed branching.
- Design an
AccessControlPolicyaggregate with roles and permissions. - Prevent duplicate permission assignment bugs.
- Design a
TravelItinerarymodel with legs and total duration calculations. - Prevent invalid overlapping travel legs.
- Design a
PatientQueuemodel with priority and arrival order. - Prevent queue corruption after reprioritization.
- Design an
Auctionaggregate with bids and close rules. - Prevent late bids after close time.
- Design a
ScoreBoardaggregate with rounds and participants. - Prevent out-of-order round score entry.
- Design a
LoanApplicationReviewprocess with multiple review decisions. - Require final decision only after mandatory checks pass.
- Design a
PolicyDocumentaggregate with versions and publish rules. - Prevent editing already published versions directly.
- Design a
RefundSettlementmodel with settlement attempts. - Prevent marking refund complete when settlement attempt failed.
- Design a
FleetMaintenanceSchedulewith service records and due checks. - Prevent closing maintenance jobs without mandatory checklist completion.
- Design a
GameMatchaggregate with players, turns, and result locking. - Prevent further moves after result declaration.
- Design a
DigitalWalletTransfermodel with sender, receiver, limits, and state. - Prevent balance deduction and receiver credit from going out of sync in domain logic.
- Design a
DonationCampaignaggregate with pledges and fulfillment status. - Prevent campaign closure when unresolved pledges exist unless explicitly allowed.
- Design a
ProcurementRequestaggregate with approval chain and vendor quotes. - Prevent quote selection before minimum vendor response count is satisfied.
- Design a
UniversitySemesterPlanaggregate with courses and credit rules. - Refactor one of the above aggregates to improve cohesion and lower coupling.
Advanced Stage 4: High-Difficulty OOP Engineering and Refactoring Challenges (901-1000)
- Refactor a deep inheritance hierarchy of vehicles into a cleaner composition-heavy design.
- Refactor a payment system where concrete classes are created directly inside services.
- Replace direct
newcalls across services with injected abstractions where appropriate. - Refactor a
UserManagerclass that handles login, reporting, email, and audit. - Extract cohesive services from that
UserManagerwhile preserving behavior. - Refactor a giant
OrderServicewith 12 responsibilities into a clear object collaboration model. - Identify aggregate roots and supporting services in that
OrderServicedesign. - Refactor a school management model where every class has public fields.
- Add invariant-protecting methods and remove direct state mutation.
- Refactor a class hierarchy where child classes constantly override methods with empty bodies.
- Diagnose why that hierarchy violates substitutability and redesign it.
- Refactor a
Birdhierarchy where some birds cannot fly without breaking behavior contracts. - Replace inheritance with capability interfaces where needed.
- Refactor a design where
instanceofchecks determine payment behavior everywhere. - Replace those checks with runtime polymorphism and strategies.
- Refactor a discount engine that modifies one giant method every festival season.
- Make the discount system open for extension and closed for modification.
- Refactor a report generator that hardcodes output format strings in business logic.
- Separate report data preparation from report rendering.
- Refactor a chat application where message sending is mixed with persistence and notification.
- Separate domain model, sender abstraction, and notification behavior.
- Refactor a product system where money is modeled as
doubleeverywhere. - Introduce a
Moneyvalue object and explain where API boundaries change. - Refactor an order model where
statusis a raw string used in many places. - Replace string status with safer domain modeling and explicit transitions.
- Refactor a booking system where seat selection, payment, and ticket issuance are tightly coupled.
- Separate them into collaborating objects without losing consistency.
- Refactor a reporting system that returns large mutable internal collections.
- Prevent clients from mutating internal aggregate state accidentally.
- Refactor a customer service model where comments, escalations, and assignment are all methods on one class.
- Improve cohesion and event traceability.
- Refactor a batch job framework where each job contains logging, error handling, retry, and business logic mixed together.
- Separate cross-cutting concerns from job-specific logic.
- Refactor an exam system where all question types use one giant class with many nullable fields.
- Replace it with a more explicit object model.
- Refactor a loyalty program where tier logic is duplicated in multiple services.
- Centralize tier rules without creating a god class.
- Refactor a payroll system where different pay rules are encoded with nested
if-elsetrees. - Introduce a pay-rule abstraction and explain testing benefits.
- Refactor a warehouse system where inventory counts can become inconsistent because updates happen from multiple places.
- Centralize mutation paths inside a proper aggregate.
- Refactor a media player model where state logic is spread across UI and domain classes.
- Introduce a better state-oriented design.
- Refactor a cart system where discounts and taxes are applied in inconsistent order across codebase.
- Model pricing pipeline explicitly.
- Refactor a user-notification system where each service chooses its own notification formatting rules.
- Centralize message composition without hard-coding sender channel behavior.
- Refactor a support-ticket workflow that allows invalid status jumps due to open setters.
- Replace open setters with explicit domain operations.
- Refactor an invoice model where invoice totals are recalculated on every getter call from mutable lines.
- Make invoice snapshots stable and predictable.
- Refactor a cab booking system where fare, trip, and driver availability are changed by multiple services independently.
- Identify consistency boundaries and redesign around them.
- Refactor a document approval system where permissions are checked ad hoc in many methods.
- Introduce clear policy abstractions or authorization services.
- Refactor a fitness app where workout, nutrition, and subscription logic live in one large member class.
- Split responsibilities while maintaining a coherent domain.
- Refactor an e-commerce product model where digital and physical products share wrong inheritance.
- Replace fragile inheritance with capabilities or composition.
- Refactor a shopping cart system to support plug-in pricing rules from external teams.
- Design extension points without exposing domain internals dangerously.
- Refactor a monolithic billing class to support auditability of each applied rule.
- Introduce objects representing intermediate calculation stages where needed.
- Refactor a survey platform where all answer types are strings.
- Model answer types explicitly and validate them polymorphically.
- Refactor a game engine where weapons are subclasses of characters due to bad inheritance.
- Correct the model with composition and explain why.
- Refactor a loan approval flow where rule ordering changes frequently and is brittle.
- Introduce configurable rule objects and a rule engine coordinator.
- Refactor a codebase where constructors perform database calls, network calls, and validation all together.
- Split object construction, validation, and infrastructure concerns appropriately.
- Refactor a command-processing app where handler selection is hardcoded in controller logic.
- Move to a registration-based or map-based polymorphic dispatch design.
- Refactor a report-export subsystem to support streaming large outputs without changing callers.
- Redesign abstractions so scalability concern does not leak badly.
- Refactor a school result system where one object both stores marks and renders HTML reports.
- Improve cohesion and testing ability.
- Refactor a package-shipping workflow where address parsing logic is scattered.
- Introduce a proper address value object and supporting parser boundary.
- Refactor a user-account model where security-sensitive fields are mutable from UI layer directly.
- Introduce safe mutation APIs and boundary validation.
- Refactor a collaborative editing model where document changes are applied by arbitrary services.
- Centralize change application and versioning rules.
- Refactor an audit system where every service creates audit entries in different formats.
- Introduce consistent audit abstractions without overengineering.
- Refactor a chat moderation system where blocked content checks are duplicated.
- Create a reusable moderation rule model.
- Refactor a travel itinerary system where each transport type duplicates scheduling rules.
- Extract common scheduling behavior without forcing invalid inheritance.
- Refactor a CRM where customer, lead, and prospect models share partial overlapping state badly.
- Decide which parts belong in shared abstractions and which do not.
- Refactor a parking lot system that stores all vehicles in one mutable map with weak invariants.
- Introduce stronger domain boundaries and behavior-rich slot assignments.
- Refactor a marketplace checkout system to support future split payments and partial refunds.
- Prepare the object model for those changes with minimal rewrite risk.
- Refactor a ride-sharing domain where one huge class handles rider, driver, payment, and trip status.
- Break it into proper entities, value objects, and services while preserving the workflow.
- Choose one earlier advanced system and redesign it to maximize low coupling and high cohesion.
- Choose one earlier advanced system and redesign it to maximize testability and replaceable dependencies.
- Design and implement a complete interview-grade OOP mini-system of your choice, then write a design note explaining where you used encapsulation, abstraction, polymorphism, composition, immutable value objects, and dependency inversion.
Closing Note
If a student solves this entire sheet honestly, OOP will stop feeling like a classroom chapter and start feeling like an engineering discipline.
That is exactly the point.
#oops#practice-time#just-do-it
Found this useful?
Related Posts
Comments (0)
No comments yet. Be the first to share your thoughts!