Thursday, January 24, 2013

Encapsulation in Java

Encapsulation is very useful feature of OOP concept when we are talking about security in java.

As you aware that, if we declare any varibale or method as a private then it can't be accessible in  other class or packages.
But here java provides this features to get those values, you would be thinking how ?
Yes it can be achieved by declaring getter setter methods of those particulate private members.

Like ,

package com.jignesh.brainbench;

public class EncapTest {
    private String name;
    private String idNum;
    private int age;

public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getIdNum() {
        return idNum;
    }
    public void setIdNum(String idNum) {
        this.idNum = idNum;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }

}

Now you can access all the public getter methods to read the value of those private variables.
Here you would be clear that how it can be useful for security purpose.
you would not knowing that where exact it will be stored but you can achieve this values.

Benefits :
  • 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.

No comments:

Post a Comment