2. What is Encapsulation in OOPS?
Encapsulation is a fundamental concept in object-oriented
programming (OOP) that involves bundling data and the methods
that operate on that data within a single unit, known as a class.
This concept helps to protect the data and methods from outside
interference, as it restricts direct access to them.
In other words, encapsulation involves wrapping data and methods
within a class to create a protective barrier around them.
In the book "Object-Oriented Analysis and Design," Grady Booch
defines encapsulation as "the process of compartmentalizing the
elements of an abstraction that constitute its structure and
behavior.
3. What is Encapsulation in OOPS?
Encapsulation separates the contractual interface of an
abstraction and its implementation." In other words,
encapsulation helps to separate the interface (public-
facing aspect of a class) from the implementation
(internal workings of the class).
This allows for flexibility in the design of a class, as the
implementation can be modified without affecting the
interface
4. Class
Defines a new data type which is used to create objects of that
type.
It is a template or blueprint from which objects are created.
Object :
An object is an instance of a class.
5. Object
An entity that has state and behaviour is known as an object
e.g. chair, bike, marker, pen, table, car etc.
It can be physical or logical (tangible and intangible).
6. Object - Example
Pen is an object.
State:
name is Reynolds,
color is blue
Behavior:
It is used to write, so writing is its behavior.
7. Object Characteristics
An object has three characteristics:
1. state: represents data (value) of an object.
2. behavior: represents the behavior (functionality) of an
object such as deposit, withdraw etc.
3. identity: Object identity is typically implemented via a
unique ID.
9. Example – Car Class
We've learned that encapsulation involves bundling data and
related methods in order to protect data and facilitate
communication. Let's look at an example to further illustrate this
concept.
Imagine a car (any model will work). Now, think about the various
components that make up the car, such as model, speed, engine,
speed limit, etc.,. These components can be thought of as data
attributes of the class "Car".
Now, consider actions that a car can perform, such as driving,
stopping, setting speed, honking, etc. These actions can be
thought of as the methods of the "Car" class.
10. Example Car Class cont.,
In the above example, we can see how encapsulation is
used to group together data attributes within the "Car"
class, along with the methods that operate on those
components.
This bundling helps to abstract the inner workings of the
car from the user.
For example, we don't need to know how the engine work
in order to drive the car.
11. Example - Car Class cont.,
We simply use the interface provided by the methods
(such as steering and moving) to complete the task.
This is the essence of abstraction, where client is only
concerned about the interface to achieve a specific goal,
without worrying about the internal mechanism.
So encapsulation and abstraction work together to create
a clear separation between the interface and
implementation of a class, making it easier to understand
and maintain the code
13. How to Hide Information via Encapsulation?
Object-oriented programming languages provide access
modifiers to control visibility and accessibility of class-
level structures and hide sensitive data from users.
Programmers should use these access modifiers to
differentiate between public and non-public interface of
an object.
In object-oriented programming, there are four different
types of access modifiers: public, private, protected and
default.
14. How to Hide Information via Encapsulation?
public: The public access modifier has a broad scope. It implies
that public class members (classes, methods, or data members)
can be accessed from any class, regardless of package or
relationship.
private: The class members declared private are limited to the
scope of the class and can be accessed only by the member
methods inside the class. In other words, they can not be
accessed directly by any object or method outside the
class.
15. How to Hide Information via Encapsulation?
protected: The protected class members' access level or scope is
limited to within the current or same package, as well as from
another package if and only if a class is inherited from another
package.
default: It is not a keyword; nonetheless, if no access modifier
keyword is defined, it will be used as default. The default members'
access is limited to the current or the same package. Classes that are
not in the same package cannot access or use the default members.
16. Syntax to encapsulate data and methods within a Class
Syntax
class className
{
type instance_variable1;
type instance_variable2;
. . .
type instance_variableN;
returnType method1(parameter_list)
{
//body of the method
}
. . .
returnType methodN(parameter_list)
{
//body of the method
}
}
Data or variables defined within a class are called instance
variables. However, static variables are called class variables.
17. Example – Employee Class
class Employee
{
private int ID, joinYear;
private String employeeName;
public Employee(int id, string name, int year) {
ID = id;
employeeName = name;
joinYear = year;
}
int getId() {
return ID;
}
String getName(){
return employeeName;
}
int getYear() {
return joinYear;
}
void setId(int newID){
ID = newID
}
void setName(string newName) {
employeeName = newName
}
void setYear(int newYear) {
joinYear = newYear
}
}
18. Example – Employee Class
In this example, "Employee" class has been defined with
three data members (ID, name, and joinyear) and six
methods (getId(), getName(), getYear(), setId(),
setName(), and setYear()). This code demonstrates
encapsulation in several ways:
Data bundling: All details related to an employee are
bundled together within the "Employee" class.
Data hiding: Data members are marked as private, which
means they can only be accessed directly within the class.
This help us to protect the data from outside
interference.
19. The idea here is to hide implementation complexity inside
an object and keep various objects as independent from
each other as possible.
Ideally, interface is exposed in a way that is simple for
other objects to understand, because for most problems,
clients don’t really care about implementation details.
So an interface can capture just features relevant to the
client, which is much simpler than the full
implementation.
20. Constructors provide a good mechanism to support
encapsulation. By designing proper constructors, we can
properly initialize our encapsulated data.
To access values, class usually provides publicly accessible
methods (getters and setters), which other client classes
call to retrieve and modify the values within the object.
Within a class, getter method is a method that allows
user to access values stored in data members, whereas
setter method allows user to set values of data members.
21. Example – Student Class
class Student
{
private String regNo, name;
private float cgpa;
public Student(String rn, String n, float cgpa){
regNo=rn;
name = n;
this.cgpa = cgpa;
}
public String getRegNo() {
return regNo;
}
public void setRegNo(String regNo) {
this.regNo = regNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getCgpa() {
return cgpa;
}
public void setCgpa(float cgpa) {
this.cgpa = cgpa;
}
}
23. Example of Method Encapsulation
class FencingCost_Rectangle {
private int length, breadth, costPerFeet;
public void set_values (int l,int b, int c){
length = l;
breadth = b;
costPerFeet = c;
}
private int perimeter() {
return (2*(length+breadth));
}
public fencingCost(){
System.out.println(perimeter() * costPerFeet);
}
Class Main{
public static void main(String[] a){
FencingCost_Rectangle obj1 = new FencingCost_Rectangle();
obj1.set_values(2,3,10);
obj1.fencingCost();
obj1.perimeter(); //Error:perimeter() is a private method.
}
24
24. Example of Class Encapsulation
25
class OuterClass {
...
private class NestedClass {
...
}
}
Reasons for using Class Encapsulation
It is a way of logically grouping classes that are only used in one place: If a class is
useful to only one other class, then it is logical to embed it in that class and keep the
two together. Nesting such "helper classes" makes their package more streamlined.
It increases encapsulation: Consider two top-level classes, A and B, where B needs
access to members of A that would otherwise be declared private. By hiding class B
within class A, A's members can be declared private and B can access them. In
addition, B itself can be hidden from the outside world.
It can lead to more readable and maintainable code: Nesting small classes within
top-level classes places the code closer to where it is used.
26. Effect of Reuse on using Encapsulation
Encapsulated code or unit can be reused anywhere inside the application or
across multiple applications. It is easy to change and adapt to new
requirements.
For example, if you have Student class or any other class in your application
you can reuse that class wherever needed.