MainMenu

Home Java Overview Maven Tutorials

Sunday, 15 January 2017

Encapsulation in Java with example

Encapsulation in Java with example:


For Video : CLICK HERE



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
------------------------------------------------------------------------

Tags :What is Encapsulation?,Encapsulation Example in Java

No comments:

Post a Comment