Encapsulation
Encapsulation
Example, Advantage
The process of binding data and
corresponding methods (behavior) together
into a single unit is called encapsulation
in Java.
In other words, encapsulation is a
programming technique that binds the
class members (variables and methods)
together and prevents them from being
accessed by other classes.
Thereby, we can keep variables and
methods safes from outside interference
and misuse.
Every Java class is an example of
encapsulation because we write everything
within the class only that binds variables
and methods together and hides their
complexity from other classes.
Another example of encapsulation is a
capsule. Basically, capsule encapsulates
several combinations of medicine.
If combinations of medicine are variables
and methods then the capsule will act as a
class and the whole process is called
Encapsulation as shown in the below
figure.
Realtime Example 1:
School bag is one of the most real
examples of Encapsulation. School bag
can keep our books, pens, etc.
Realtime Example 2:
When you log into your email accounts
such as Gmail, Yahoo Mail, or Rediff
mail, there is a lot of internal processes
taking place in the backend and you have
no control over it.
When you enter the password for logging,
they are retrieved in an encrypted form and
verified, and then you are given access to
your account.
You do not have control over it that how
the password has been verified. Thus, it
keeps our account safe from being
misused.
Realtime Example 3:
Suppose you have an account in the bank.
If your balance variable is declared as a
public variable in the bank software, your
account balance will be known as public,
In this case, anyone can know your
account balance. So, would you like it?
Obviously No.
So, they declare balance variable as private
for making your account safe, so that
anyone cannot see your account balance.
The person who has to see his account
balance, will have to access only private
members through methods defined inside
that class and this method will ask your
account holder name or user Id, and
password for authentication.
Thus, we can achieve security by utilizing
the concept of data hiding. This is called
Encapsulation in Java.
How to achieve or implement
Encapsulation in Java
Program code 1:
package encapPrograms;
public class Student
{
private String name;
public String getName()
{
return name;
}
public setName(void String studentName)
{
name = studentName;
}
}
class EncapsulatedTest
{
public static void main(String[] arg)
{
Student obj = new Student();
obj.name = "Amit"; // Compilation
error. Since name is private.
String studentName = obj.name; //same
as above.
}
}
To remove the compilation error problem
from the above code, we need to call the
getter, getName(), and the setter setName()
to read and update the value of variable.
class EncapsulationTest
{
public static void main(String[] args)
{
Student obj = new Student();// Creating
object of Student class by using new
keyword.
obj.setName("Amit"); // setting the
value of variable.
String studentName = obj.getName(); //
reading the value of variable.
System.out.println(studentName);
}
}
Output:
Amit
Program code 2:
package encapPrograms;
public class Student
{
// Step 1: Declare variables as private in
the class.
private String stdName; // private field.
private int stdRollNo; // private field
private int stdId;
Output:
Drawing 10
Java Lambda Expression Example
Now, we are going to implement the above
example with the help of Java lambda
expression.
@FunctionalInterface //It is optional
interface Drawable{
public void draw();
}
//with lambda
Drawable d2=()->{
System.out.println("Drawing "+wid
th);
};
d2.draw();
}
}
Test it Now
Output:
Drawing 10
interface Addable{
int add(int a,int b);
}
this();
this("Javatpoint");
Let's create a Java program and call the
current class constructor.
ConstructorChain.java
}
Output:
// Main class
class Sample {
// Class 1
class Sample {
protected int year = 2021;
protected void printYear() {
System.out.println("Its
"+year+" !!");
}
}
// Class 2
public class Test {
// Main driver method
public static void main(String[] args) {
Sample sample = new Sample();
System.out.println(sample.year);
sample.printYear();
}
}
Output
2021
Its 2021 !!
Case 3: Accessing protected members of a
class in its subclass in the same package
// Java Program to Illustrate
// Accessing Protected Members
// of a class in its subclass
// in the same package
// Class 1
class Sample {
static protected String title =
"geekforgeeks";
protected int year = 2021;
protected void printYear() {
System.out.println("Its
"+year+" !!");
}
}
// Class 2
public class Test extends Sample {
public static void main(String[] args) {
Sample sample = new Sample();
System.out.println(sample.year);
sample.printYear();
System.out.println(Sample.title);
}
}
2021
Its 2021 !!
geekforgeeks
Case 4: Accessing protected members in
another class in a different package
We cannot access the protected members
of a class in a class (non-subclass) that is
present in a different package.
// Java Program to Illustrate Accessing
Protected
// Members in sub-class in a different
package
package package1;
// Class
public class Sample {
// Protected attributes
static protected String title =
"geeksforgeeks";
protected int year = 2021;
protected void printYear()
{
System.out.println("Its " + year +
" !!");
}
}
// Main class
public class Child extends Sample {
// Method 1
void helper()
{
System.out.println(year);
printYear();
System.out.println(Sample.title);
}
// Method 2
// Main driver method
public static void main(String[] args)
{
class Employee {
{
// It is sub block to keep
// all those interns.
Employee X = new
Employee("GFG4", 23);
Employee Y = new
Employee("GFG5", 21);
X.show();
Y.show();
X.showNextId();
Y.showNextId();
X = Y = null;
System.gc();
System.runFinalization();
}
E.showNextId();
}
}
Output
Id=1
Name=GFG1
Age=56
Id=2
Name=GFG2
Age=45
Id=3
Name=GFG3
Age=25
Next employee id will be=4
Next employee id will be=4
Next employee id will be=4
Id=4
Name=GFG4
Age=23
Id=5
Name=GFG5
Age=21
Next employee id will be=6
Next employee id will be=6
Next employee id will be=4