Encapsulation in Java
In Java, when you create a new class (ADT), inside your class declaration, you will be declaring data elements / properties and methods / functions. Encapsulation is a process or an entity that is, Encapsulation is the process of bundling data elements and operations (methods) on the data together in an entity or it is an act of bundling one or more items into a container called entity (class). For example,
Person.java
//************** ENCAPSULATION with or without hiding any information*******************
package encapsulation;
/* Person class is an encapsulation of the data elements & methods...
Person class uses information hiding by hiding the data elements from the outside world */
public class Person { // new abstract data types (ADT).
//ENCAPSULATION with hiding any information*******************
private String name; /* data elements, are bundled together in a class called Person */
private String gender;
//ENCAPSULATION without hiding any information*******************
// public String name; // Data Elements Are Not Hidden..
// public String gender; // Data Elements Are Not Hidden ...
public Person(String initialName, String initialGender) { // set of operation...
//Hiding of the data representation from its users
name = initialName; /* methods, are bundled together in a class called Person. */
gender = initialGender;
}
public String getName() { // set of operation...
return name;
}
public void setName(String newName) { /* set of operations that can be applied to all its data objects. */
name = newName;
}
public String getGender() { // set of operation..
return gender;
}
}
PersonTest.java
package encapsulation; public class PersonTest { public static void main(String a[] ) { /* Users view the data objects of an ADT (Person) in an abstract way by applying these four operations... */ /* Note: client code are written in terms of the specifications of the four operations, given by Person type and not their implementation. */ Person john = new Person("John Jacobs", "Male"); String intialName = john.getName(); String gender = john.getGender(); john.setName("Wally Jacobs"); System.out.println("Person Name :"+ intialName +" " + "Gender :" + gender); String changedName = john.getName(); } }