Sunday, 10 September 2017

Encapsulation

What is encapsulation?

Encapsulation hides implementation details from user.

Encapsulation is process of wrapping code and data together into a single unit.

In Car, there is power steering mechanism, this is very complex system. It have lots of parts internally, they works together to turn the car in the desire direction.  It even controls the power bring by the engine to the steering wheel. But to the external world there is only one interface is existing and relax of the complexity is hidden. Furthermore, the steering unit in itself is complete and self-determining. It does not affect the performance of any other mechanism.

Encapsulation is also known as "Data hiding" because they are protecting data.

Access modifiers (private, public, protected) restrict access to data at different levels.


public class StudentDemo{
    private int ssn;
    private String stuName;
    private int stuAge;

    //Getter and Setter methods
    public int getStuSSN(){
        return ssn;
    }

    public String getStuName(){
        return stuName;
    }

    public int getStuAge(){
        return stuAge;
    }

    public void setEmpAge(int newValue){
        stuAge = newValue;
    }

    public void setEmpName(String newValue){
        stuName = newValue;
    }

    public void setEmpSSN(int newValue){
        ssn = newValue;
    }
}
public class MyEncapsulationTest{
    public static void main(String args[]){
         StudentDemo obj = new StudentDemo();
         obj.setStuName("Mir");
         obj.setStuAge(21);
         obj.setStuSSN(2142);
         System.out.println("Student Name: " + obj.getStuName());
         System.out.println("Student SSN: " + obj.getStuSSN());
         System.out.println("Student Age: " + obj.getStuAge());
    }
}
Example Code


As you can see in the above examples, encapsulation is implemented in Java using interfaces, classes, access modifiers, setters and getters.

Encapsulated Code is more flexible and easy to change with new requirements.

Objects encapsulate data and implementation details. To the outer surface world, an object is a black box that exhibits a certain behavior.


The fields can be made read-only or write-only. Where we can declare variable as a private we can access it from the method which is using that private variable.

0 comments:

Post a Comment