Encapsulation in Java Programming
Previous | Home | Next |
Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods.
Benefits of Encapsulation:
The fields of a class can be made read-only or write-only.
A class can have total control over what is stored in its fields.
The users of a class do not know how the class stores its data. A class can change the data type of a field, and users of the class do not need to change any of their code.
Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods.
If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the
class. For this reason, encapsulation is also referred to as data hiding.
The main benefit of encapsulation is the ability to modify our implemented code without breaking the code of others who use our code. With this feature Encapsulation gives maintainability, flexibility and extensibility to our code.
/* File name : Encap.java */
public class Encap
{
private String name;
private String IdNum;
private int age;
public int getAge()
{
return age;
}
public String getName()
{
return name;
}
public String getidNum()
{
return IdNum;
}
public void setAge( int newAge)
{
age = newAge;
}
public void setName(String newName){
name = newName;
}
public void setidNum( String newId)
{
IdNum = newid;
}
}
/* File name : RunEncap.java */
public class RunEncap
{
public static void main(String args[])
{
Encap encap = new Encap();
encap.setName("Nancy");
encap.setAge(21);
encap.setidNum("25364nm");
System.out.print("Name : " + encap.getName()+
" Age : "+ encap.getAge());
}
}
Name:Nancy Age:21
Previous | Home | Next |