You are on page 1of 22

Encapsulation

Course Code: CSE- 412 Course Title: Programming with JAVA

Dept. of Computer Science


School of Science and Technology

Lecturer No: 7 Week No: 4 Semester: Summer 2022


Lecturer: Mohammed Ashikur Rahman
Lecture Outline

1. Introduction to Encapsulation
2. Information Hiding
3. Access control
4. Example
Introduction to Encapsulation
What is Encapsulation?

❑ Encapsulation is a primary attribute to OOP.


❑ Encapsulation is the mechanism that binds code and
function that manipulates the data together and keeps
both safe from outside interference and misuse.
Information Hiding
Encapsulation is a form of protection

❑ Encapsulation is as a protective wrapper that prevents the


code and data from being arbitrarily accessed by other code
defined outside the wrapper.
❑ So, the outside world does not have direct access to the
internal implementation.
❑ By hiding data and providing methods to gain access to it, an
object can maintain high data integrity
❑ Methods have the responsibility of maintaining data integrity
❑ The encapsulate class is easy to test. So, it is better for unit
testing.
Benefits of encapsulation
� Protects object from unwanted access
� Example: Can't fraudulently increase an Account's balance.

� Can change the class implementation later


� Example: Point could be rewritten in polar
coordinates (r, θ) with the same methods.
Access Control
What is Access Control

❑ Encapsulation provides another important attribute: Access


Control
❑ There are two levels of access control:
❑ At the top level—public, or package-private (no explicit
modifier).
❑ At the member level—public, private, protected, or
package-private (no explicit modifier).
❑ Access level modifiers determine whether other classes can
use a field or invoke a method.
Access Control
Controlling Access to Members of a Class

❑ At the top level—public, or package-private (no explicit


modifier).
❑ public
❑ A class may be declared with the modifier public, in
which case that class is visible to all classes
everywhere.
❑ Package-private
❑ If a class has no modifier (the default, also known as
package-private), it is visible only within its own
package. (We will understand more about
package-private, when we will study about packages).
Access Control
Controlling Access to Members of a Class

❑ At the member level—public, private, protected, or


package-private (no explicit modifier).
❑ public
❑ The public access modifier has the widest scope among
all other access modifiers.
❑ Methods or data members which are declared as public
are accessible from every where in the program. There
is no restriction on the scope of a public data members.
❑ private:
❑ The private modifier specifies that the member can only
be accessed in its own class.
Access Control
Controlling Access to Members of a Class

❑ protected
❑ The protected modifier specifies that the member can
only be accessed within its own package (as with
package-private).
❑ In addition, by a subclass of its class in another package.
❑ package-private:
❑ The data members or methods which are not declared
using any access modifiers i.e. having default access
modifier are accessible only within the same package.
Access Control
Understanding Java Access Modifiers

Access within within outside outside


Modifier class package package by package
subclass only
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
Access Control
How to Achieve Encapsulation using Access Control Mechanism

❑ As we know, encapsulation links data with the code that


manipulates it.
❑ Through encapsulation, we can control what parts of a program
can access the members of a class.
❑ 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
Example
Check the Code
Public class BMI {
Public static double KgPerPound = 0.45;
Public static double MeterPerInch = 0.0254; Output
The BMI for Tanvin is (20.80)
private String name;
Normal
Private double weight, height;
Public BMI (String name, double weight, double height) { ….}
Public double getBMI () {double bmi =(weight / [height (in)]2) x 703; …}
Public String getStatus () {
Public class BMITest {
double bmi == getBMI ();
public static void main (String [] args) {
if (bmi < 18.5) {return “Underweight”;}
BMI bmi = new BMI (“Tanvin”, 145, 70);
else if (bmi <25) { … }
else if() { … } System.out.println (“The BMI for ” +
Public String getName () { return name;} bmi.getName() + “is (” +bmi.getBMI() +”)”
} +bmi.getStatus());
} }
}
Primitives vs. objects;
value and reference
semantics
A swap method?
� Does the following swap method work? Why or why not?
public static void main(String[] args) {
int a = 7;
int b = 35;
// swap a with b?
swap(a, b);
System.out.println(a + " " + b);
}

public static void swap(int a, int b) {


int temp = a;
a = b;
b = temp;
}
Value semantics
� value semantics: Behavior where values are copied when assigned,
passed as parameters, or returned.

� All primitive types in Java use value semantics.


� When one variable is assigned to another, its value is copied.
� Modifying the value of one variable does not affect others.

int x = 5;
int y = x; // x = 5, y = 5
y = 17; // x = 5, y = 17
x = 8; // x = 8, y = 17
Reference semantics (objects)
� reference semantics: Behavior where variables actually store the
address of an object in memory.

� When one variable is assigned to another, the object is


not copied; both variables refer to the same object.
� Modifying the value of one variable will affect others.

int[] a1 = {4, 15, 8};


int[] a2 = a1; // refer to same array as a1
a2[0] = 7;
System.out.println(Arrays.toString(a1)); // [7, 15, 8]
index 0 1 2
a1 value 4
7 15 8 a2
References and objects
� Arrays and objects use reference semantics. Why?
� efficiency. Copying large objects slows down a program.
� sharing. It's useful to share an object's data among methods.

DrawingPanel panel1 = new DrawingPanel(80, 50);


DrawingPanel panel2 = panel1; // same window
panel2.setBackground(Color.CYAN);
panel1

panel2
Objects as parameters
� When an object is passed as a parameter, the object is not copied.
The parameter refers to the same object.
� If the parameter is modified, it will affect the original object.

public static void main(String[] args) {


DrawingPanel window = new DrawingPanel(80, 50);
window.setBackground(Color.YELLOW); window
example(window);
}

public static void example(DrawingPanel panel) {


panel.setBackground(Color.CYAN);
...
}
panel
Arrays as parameters
� Arrays are also passed as parameters by reference.
� Changes made in the method are also seen by the caller.
public static void main(String[] args) {
int[] iq = {126, 167, 95}; iq
increase(iq);
System.out.println(Arrays.toString(iq));
}
public static void increase(int[] a) {
for (int i = 0; i < a.length; i++) {
a[i] = a[i] * 2;
} index 0 1 2
}
a value 126 334
252 167 19095
� Output:
[252, 334, 190]
Books

1. Java The Complete Reference- Ninth Edition by Herbert Schildt


References

• https://docs.oracle.com/javase/tutorial/

You might also like