Task 10 - Interfaces and Exception Handling in Java

Create a UserService Interface with following methods.

void addUser(User user)
void updateUser(User user)
void deleteUser(int userID)
User getUser(int userID)
void unblockUser(int userID)
void blockUser(int userID)
ArrayList<User> getAllUsers()

Define InMemoryUserService class that shall implement UserService contract or interface. Use ArrayList for storage, update and retrieve operations inside InMemoryUserService i.e. you shall define a static attribute ArrayList<User> users = new ArrayList<>(); The implemented methods shall change/read this list to perform the required operation. Test all methods from UserTest class. Getting information from user input is encourged but optional. 

Define at least id, name, and status instsance attributes in User class of type int, String and Boolean. How you check whether a user account is blocked? If status attribute is false, it means user account is blocked. True represent the account is active.

Make a test class to test the functionality of UserService ... no need to take inputs from user. Just call its different methods to see how it works, keep printing related information on console to show what the program is doing.

If you have studied exception handling by now, improve above code using exception handling as explained below. Otherwise, skip below requirements at the moment. 

Change addUser and getUser methods declaration in the interface as follows:
void addUser(User user) throws UserAlreadyExistException
User getUser(int userID) throws UserAccountIsBlockedException

UserAlreadyExistException exception shall be thrown if user already exist in the users array list. The exception object shall also store the 
user ID for which the exception occured. Check using equals methods (override the method in User class, based on user ID). Make UserAlreadyExistException a runtime exception. UserAccountIsBlockedException should be thrown if status attribute of the user object (in the array list) is false. Define this exception as checked.

Update the test class by handling both exceptions. Call different methods passing parameters that shall make the user service to throw the exception to demonstate you handled them appropriately.


For solution of this task, visit: http://www.bitspedia.com/2017/12/java-interfaces-and-exception-handling.html


Popular posts from this blog

Task 12 - Create Java Program with MySQL Database Connectivity

Java Interfaces and Exception Handling - Practice Problem with Solution

Task 16 - Javafx Program to Create, Retrieve, Update and Delete records with Database