CS F213 Objected Oriented Programming Labsheet 2
Spring 2024
Access Modifiers in Java
Access modifiers help to restrict the scope of a class, constructor, variable, method, or data member. It provides security, accessibility, etc to the user depending upon the access modifier used with the element.
Package
A package
in Java is used to group related classes. Think of it as a folder in a file directory. We use packages to avoid name conflicts, and to write a better maintainable code.
Example:
In the example above, java.util
is a package, while Scanner
is a class of the java.util
package
Types of Access Modifiers in Java
Default : When no access modifier is specified for a class, method, or data member – It is said to be having the
default
access modifier by default. The data members, classes, or methods that are not declared using any access modifiers i.e. having default access modifiersare accessible only within the same package.
Private : The private access modifier is specified using the keyword
private
. The methods or data members declared as private areaccessible only within the class in which they are declared.
Any other class of the same package will not be able to access these members.
Protected : The protected access modifier is specified using the keyword
protected
. The methods or data members declared as protected areaccessible within the same package or subclasses in different packages.
Public : The public access modifier is specified using the keyword
public
. The public access modifier has the widest scope among all other access modifiers. Classes, methods, or data members that are declared as public areaccessible from everywhere in the program
. There is no restriction on the scope of public data members.
Summary:
Same Class
Yes
Yes
Yes
Yes
Same Package Class
No
Yes
Yes
Yes
Same Package Sub-Class
No
Yes
Yes
Yes
Other Package Class
No
No
No
Yes
Other Package Sub-Class
No
No
Yes
Yes
In Java, as in other object-oriented programming languages, classes can be derived from other classes. The derived class (the class that is derived from another class) is called a
subclass
. The class from which its derived is called the superclass.
Encapsulation in Java
Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism that binds together code and the data it manipulates. Another way to think about encapsulation is, that it is a protective shield that prevents the data from being accessed by the code outside this shield.
Encapsulation gives control to the programmer to decide what aspects of the code can be accessed/manipulated from different scopes
As a good practice, in encapsulation, the variables or data of a class are hidden from any other class and are allowed access only through a member function of its own class in which it is declared.
As in encapsulation, the data in a class is hidden from other classes using the data hiding concept which is achieved by
making the members or methods of a class private
This level of encapsulation can be achieved by declaring all the variables in the class as private and writing
public methods in the class to set and get the values of variables
Example:
Explanation:
The getter methods returns the value of the variable name and the setter methods take a parameter (e.g. name) and assigns it to the variable. The this keyword is used to refer to the current object.
However, as the name variable is declared as private, we cannot access it from outside this class:
The above code would result in an error
:
So instead of using the variable we use the getter and setter
methods we made in the Person class. So our Main class would look like:
The Java
new
keyword is used to create an instance of the class. In other words, it instantiates a class by allocating memory for a new object and returning a reference to that memory. We can also use the new keyword to create the array object.
Why Encapsulation?
Better control of class attributes and methods
Class attributes can be made
read-only (if you only use the get method), or write-only (if you only use the set method)
Flexible: the programmer can change one part of the code without affecting other parts, as long as the getter and setter APIs don't change
Increased security of data
Exercise Problems:
Exercise 1
Implement a simple calculator program
that performs basic arithmetic operations. The calculator should support addition, subtraction, multiplication, and division. Use a switch statement
to handle the different operations.
Implement a method called doCalculate()
that takes three parameters: number1 (double)
, number2 (double)
, and operator (char)
. The method should perform the arithmetic operation specified by the operator
on number1
and number2
. Display an error message if an invalid operator is provided. Round the result to two decimal places.
Input
num1 (double): The first operand.
num2 (double): The second operand.
operator (char): The arithmetic operator (+, -, *, /)
Output
The result of the arithmetic operation rounded to two decimal places
Sample Test Input
Sample Test Output
Exercise 2
Design a simple program to calculate the final amount to be repaid for a loan. Create a Customer
class with encapsulated attributes
to represent customer details and loan information.
name (String) time (int) - representing the loan period in years interestRate (double) - representing the annual interest rate principalAmount (double) - representing the initial loan amount
Implement getter and setter
methods for each member variable to encapsulate access to these attributes.
Create a method named calculateFinalAmount
within the Customer class that calculates the final amount to be repaid. (You can use the same code of Exercise 2, Lab 1)
In the main class take input from the user for the customer's details and loan information. Use setter methods to set the attributes of the Customer class. Use getter methods to retrieve the values and calculate the final amount using the calculateFinalAmount method.
Display all the details, including the customer's name, loan period, interest rate, principal amount, and the final amount.
Sample Test Input
Sample Test Output
Exercise 3
Create a simple login system using Java. Implement a Database
class that stores user information, including Name, Unique ID (6 digits) and a PIN (4 digits). The name and Unique ID are read-only, while the PIN can be both read and modified.
name (String) = "John" unique_id (int) = 202189 PIN (int) = 2580
Create a method named changePIN()
within the Main class that takes user input for a new PIN and updates the PIN using the setter method.
In the main class implement a menu-driven program
with the following options:
Login (Option 1): Prompt the user to enter their Unique ID and PIN. If the entered details match the stored Unique ID and PIN, display "Login successful, welcome [Name]", where [Name] is the user's name. Otherwise, print "Wrong details, please check."
Change Password (Option 2): Ask the user to enter a new PIN and update the PIN using the changePIN method. Display "PIN Changed Successfully" after a successful PIN change.
Exit (Option 3): Terminate the program.
Sample Test Input 1
Sample Test Output 1
Sample Test Input 2
Sample Test Output 2
***
Last updated