Thursday, April 29, 2010

Encapsulation in JAVA

Encapsulation in java means declare instance variables of class as private and access that instance variables using public methods.
Following is the example which shows that Person class having name and age are private instance variables and those are accessed by public getter and setter methods.

public class Person {
    private String name;
    private int age;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}



2 comments:

  1. This question was asked to me in Cognizant, Fundtech and Wipro technical interviews.

    ReplyDelete
  2. What's need to make variable private and write methods public??
    we can declare variable public and directly set their value??
    Please explain this with example

    ReplyDelete