{ }codelper

Java Classes and OOP Practice Problems

Just reading class syntax does not show you when to use it. Work through these 24 problems in order: group data, add methods, and swap implementations behind an interface.

24 problemsLevel 2–5Solve in Java

1. Grouping data together #1–6

Put values that travel together, like a name and a score, into one class.
For a group that only holds values, one line is enough: record Student(String name, int score) {} (since Java 16).
Keep several of them in a List<Student>, and sort by giving the order, as in Comparator.comparing(Student::score).

  1. Weekend farm plot records8P0319
  2. Score ranking8P0067
  3. Orders by city2P0082
  4. Parcel trucks that leave when full8P0247
  5. Top k per stage2P0122
  6. Matching the product table and the order table2P0160

2. Classes and methods #7–14

Hide fields with private and let only methods change their values.
Set the starting state in the constructor.
Between objects, == asks whether they are the same object, so compare contents with equals (the same goes for strings).

  1. Café stamp cards6P0261
  2. A game character that reports its own status6P0346
  3. Bank account objects6P0078
  4. Shared ticket numbers6P0079
  5. A different salary for each kind of employee6P0157
  6. League table6P0080
  7. Hourglasses that run together6P0323
  8. Editing a floor plan with chained methods6P0276

3. enum #15–19

For a fixed handful of values, like days of the week or states, make an enum.
Typos are caught at compile time, and it works well with switch.
Use values() to get all of them, ordinal() to get the position number, and valueOf("MON") to get a value from its name.

  1. Which way the turtle faces6P0077
  2. Order state machine6P0156
  3. Filter logs by level6P0357
  4. Hands of five dice6P0198
  5. Alarm weekday flags6P0419

4. Interfaces #20–24

An interface is a promise that "this method exists".
Even if each shape computes its area differently, you can hold any of them as a Shape and call area().
Put @Override on the methods you implement, and the compiler tells you when you get a name wrong.

  1. Coupons used in order5P0199
  2. One max for everything3P0081
  3. Smart-home devices grouped by what they can do5P0383
  4. Task queue and median3P0121
  5. A board path that adds and caps4P0415

Good to know

See also