MainMenu

Home Java Overview Maven Tutorials

Sunday 15 January 2017

Encapsulation in Java with example

Encapsulation in Java with example:


For Video : CLICK HERE



What is Encapsulation?

The process of binding data and corresponding methods(behaviour) together into a single usint is called encapsulation in java.



Encapsulation is also known as Data hiding.
If a class have private member & it is required to access these private member from outside of class then we have to create public getter & setter method.


This way data can only be accessed by public methods thus making the private fields and their implementation hidden for outside classes.


Variables and methods are defined inside one class like a capsule.

Features of Encapsulation :-
1) Better control on class & methods
2) Class attribute can be made read only or write only.
3) Make Java code veri flexible, programmer can change one part of code without effecting other part.

To protect the data, variables must be private and they can only be accessed through methods.




Encapsulation Example 1


class chandan
{
private string Name;
private Int Age;
public string getName()
{
return Name;
}
public void setName(String Name)
{
this.Name = Name;
}
public int getAge()
{
return Age;
}
public void setAge(int Age)
{
this.Age = Age;
}
}
public class Chandan1
{
public static void main(String args[])
{
chandan obj = new chandan();
obj.setName("Chandan");
obj.setAge(25);
System.out.println("Your name is :" +obj.getName);
System.out.println("Your Age is :" +obj.getAge);
}
}
Output :
Your name is :Chandan
Your Age is :25
--------------------------------------------------------------------------------------

Encapsulation Example 2


class csc
{
private int x;
private String name;
public int getX()
{
return x;
}
public void setX(int x)
{
this.x = x;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public csc(int x, String name)
{
this.x = x;
this.name = name;
}
}

public class encap
{
public static void main(String[] args)
{
csc obj = new csc(32, "Chandan");
System.out.println(obj.getX());
System.out.println(obj.getName());
}
}

Output :
32
chandan

------------------------------------------------------------------
Advantage of Encapsulation in Java

1: The encapsulated code is more flexible and easy to change with new requirements.

2:It prevents the other classes to access the private fields.

3:It keeps the data and codes safe from external inheritance.
Thus, Encapsulation helps to achieve security.

4:It improves the maintainability of the application.

5:if you don't define the setter method in the class then the fields can be made read-only.

6:If you don't define the getter method in the class then the fields can be made write only.

------------------------------------------------------------------------

Tags :What is Encapsulation?,Encapsulation Example in Java

No comments:

Post a Comment