Encapsulation is a mechanism where you bind your data and code together as a single unit. It also means to hide your data in order to make it safe from any modification.
We can achieve encapsulation in Java by:
Declaring the variables of a class as private. Providing public setter and getter methods to modify and view the variables values.
Example :
The main advantages of encapsulation are:
Real Time Example :
take a example of news channel. Here the journalist finds the information and he only knows from where he had sourced this information.So it's source is protected inside their workplace.And the public only knows about the news. And the source is hidden.We can achieve encapsulation in Java by:
Declaring the variables of a class as private. Providing public setter and getter methods to modify and view the variables values.
Example :
package com.tutorial4u;
class Employee{
private int empNo;
private String empName;
private int salary;
public int getEmpNo() {
return empNo;
}
public void setEmpNo(int empNo) {
this.empNo = empNo;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
}
public class EncapsulationDemo{
public static void main(String[] args) {
Employee
emp = new Employee();
emp.setEmpNo(101);
emp.setEmpName("Ashish Kumar");
emp.setSalary(1000);
System.out.println("Employee No : "+emp.getEmpNo());
System.out.println("Employee Name is : "+emp.getEmpName());
System.out.println("Employee salary is : "+emp.getSalary());
}
}
Output :
Employee No : 101
Employee Name is : Ashish Kumar
Employee salary is : 1000
|
The main advantages of encapsulation are:
- We can achieve security.
- Enhancement will become very easy.
- It improves maintainability of the application.
- It provides flexibility to the user to use system very easily.
Disadvantage :
The main disadvantage of encapsulation is it increases length of the code and slows down execution.
No comments:
Post a Comment