Загрузка...

Encapsulation in Java Made EASY 🔐 (Real-Life Examples + Code)

Tasks/Assignments Coding Question :

Task 1 — Easy Easy
Create a class called Person with private fields: name (String), age (int), and city (String). Write a
constructor, getters for all fields, and setters for name and city. The setter for age must reject any value
less than 1 or greater than 120. In Main, create one Person object, set values using setters, and print
them using getters.

Task 2 — Easy to Medium Easy to Medium
Create a class called Product with private fields: productName, price (double), and quantity (int). Write
getters and setters for all fields. The price setter must reject values less than or equal to 0. The
quantity setter must reject negative values. Add a method getTotalValue() that returns price multiplied
by quantity. Test in Main with valid and invalid values.

Task 3 — Medium Medium
Create a fully encapsulated class called Employee with private fields: name, employeeId (int), salary
(double), and department (String). EmployeeId should be read-only (no setter). Write a setter for salary
that rejects values below 5000. Add a method applyBonus(double percent) that increases salary by the
percentage. Print all details before and after the bonus.
Task 4 — Challenge Challenge
Create a class called Library with private fields: bookTitle, author, totalCopies (int), and
availableCopies (int). Make availableCopies read-only (no direct setter). Write a method issuBook()
that decreases availableCopies by 1 if any are available, otherwise prints 'No copies available'. Write a
method returnBook() that increases availableCopies by 1, but not beyond totalCopies. Test all
scenarios in Main.

Видео Encapsulation in Java Made EASY 🔐 (Real-Life Examples + Code) канала LogicLabPK
Яндекс.Метрика
Все заметки Новая заметка Страницу в заметки
Страницу в закладки Мои закладки
На информационно-развлекательном портале SALDA.WS применяются cookie-файлы. Нажимая кнопку Принять, вы подтверждаете свое согласие на их использование.
О CookiesНапомнить позжеПринять