Object oriented Programming language has the different four fundaments which makes the OOP as their standard.
- Encapsulation
- Inheritance
- Polymorphism and
- Abstraction
Encapsulation definition in Java
Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data (methods) together as a single unit. In encapsulation, the variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class. Therefore, it is also known as data hiding.
To achieve Encapsulations following steps has to be done :
- Declare the variables of a class as private
- Provide public setter and getter methods to modify and view the variables values
Java program to demonstrate encapsulation
package Q9_Encapsulation;
public class EncapsulationDemo
{
public static void main(String[] args)
{
Student s = new Student();
s.setRollno(16);
s.setName("Dipendra");
System.out.println("Roll no.: " + s. getRollno());
System.out.println("Name: "+ s.getName());
}
}
class Student
{
private int rollno;
private String name;
public int getRollno()
{
return rollno;
}
public void setRollno(int rollno)
{
this.rollno = rollno;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
}