Switch to full style
Java2 codes,problems ,discussions and solutions are here
Post a reply

What is Encapsulation?

Tue Jul 03, 2007 11:57 pm

What is Encapsulation?
-----------------------------


Encapsulation provides the basis for modularity- by hiding information from unwanted outside access and attaching that information to only methods that need access to it. This binds data and operations tightly together and separates them from external access that may corrupt them intentionally or unintentionally.


Encapsulation is achieved by declaring variables as Private in a class- this gives access to data to only member functions of the class. A next level of accessibility is provided by the Protected keyword which gives the derived classes the access to the member variables of the base class- a variable declared as Protected can at most be accessed by the derived classes of the class. Using set and get methods is an example of encapsulation.
java code
public class Person {

private String FirstName;
private String LastName;
private String Age;
private String Address;

public Person(String FirstName, String LastName, String Age, String Address) {
this.FirstName = FirstName;
this.LastName = LastName;
this.Age = Age;
this.Address = Address;
}

public String getFirstName() {
return FirstName;
}

public String getLastName() {
return LastName;
}

public String getAge() {
return Age;
}

public String getAddress() {
return Address;
}

public void setFirstName(String FirstName) {
this.FirstName = FirstName;
}

public void setLastName(String LastName) {
this.LastName = LastName;
}

public void setAge(String Age) {
this.Age = Age;
}

public void setAddress(String Address) {
this.Address = Address;
}

}




Post a reply

Topic Tags

Java OOP