LearnFrenzy
Sign in Take a free test

Encapsulation · Exercise 4 of 4

Encapsulation Encapsulation Programs

  • 10 questions
  • Page 1 of 1
  • Answers explained
0Attempted
0Correct
0Wrong
Directions

Java programs that design well-encapsulated classes. Write each one yourself first, then open the solution – every solution was compiled and run on Java 21, and the output shown is the real output.

Question 1 Easy

Write a BankAccount class with a private balance, a daily withdrawal limit of ₹20,000 and a private transaction list; expose deposit, withdraw, getBalance and a read-only statement.

Question page & discussion
Question 2 Medium

Write a Cart class with a private map of product→quantity, a maximum of 5 per product, and methods add, remove, total(prices) and an unmodifiable items() view.

Question page & discussion
Question 3 Easy

Write an Employee class whose salary is private and can only change through giveRaise(percent), allowed between 1% and 30% and at most once per year; print the results of several raise attempts.

Question page & discussion
Question 4 Medium

Write a LibraryCard class that tracks borrowed books with due days privately, charges ₹5 per late day on return, blocks borrowing while fines are unpaid, and lets the member pay fines.

Question page & discussion
Question 5 Medium

Write a TemperatureLog class that stores readings privately, rejects values outside −50…60 °C, and offers min, max, average and the readings as a copy.

Question page & discussion
Question 6 Medium

Write a VotingMachine with private vote counts and a private set of voter IDs; vote(voterId, candidate) must reject unknown candidates and repeat voters, and results() must return a read-only copy.

Question page & discussion
Question 7 Hard

Write a final StudentRecord class with a name, roll number and a list of subject marks; make it fully immutable with defensive copies, and add withMark(subject, marks) that returns a new record.

Question page & discussion
Question 8 Medium

Write a Wallet class with a private balance and PIN; transferTo(other, amount, pin) checks the PIN, a ₹10,000 per-transfer limit and the balance, and moves money between wallets atomically.

Question page & discussion
Question 9 Easy

Write a ParkingMeter that accepts only ₹5, ₹10 and ₹20 coins (₹10 = 30 minutes), caps time at 3 hours, counts down with tick(minutes), and reports remaining time and collected money.

Question page & discussion
Question 10 Easy

Write a SmartBulb with private on/off state, brightness (10–100, in steps of 10) and colour; brighten/dim must work only when the bulb is on, and turning it on restores the last brightness.

Question page & discussion
All exercises doneBack to EncapsulationRevise the concepts or pick another topic

Ready to test your Programming?

Timed online tests with instant scores and explanations.

Search LearnFrenzy

Esc

Quick links