This tutorial describe concept of Encapsulation. It is one of OOPs concept.
Encapsulation in Java 7
This tutorial describe concept of Encapsulation. It is one of OOPs concept.
Encapsulation :
Encapsulation is a way of wrapping up data
and methods into a single unit. Encapsulation puts the data safe from the
outside world by binding the data and codes into single unit This is best way to
protect the data from outside the world.
By using the concept of encapsulation you can keep data safe as making them
private and you can access that by its public methods. Nobody can access these
private data outside the class so you can say encapsulation is like data hiding.
Example : Here is an example to understand the concept of encapsulation.
EncapsulationExample.java - This class contains encapsulation concept as we are declaring variables roll and name as private so that no outsider class can directly access these variables and also implementing their public setter-getter.
package encapsulation; class EncapsulationExample { private int roll; private String name; public int getRoll() { return roll; } public void setRoll(int roll) { this.roll = roll; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
EncapsulationMains.java - This is main class where we are setting value to the variable by using their setter method and getting those back by calling their getter methods.
package encapsulation; class EncapsulationMains { public static void main(String[] args) { EncapsulationExample example = new EncapsulationExample(); example.setRoll(111); example.setName("Roxi"); System.out.println("Roll No : " + example.getRoll()); System.out.println("Name : " + example.getName()); } }
Output :
Roll No : 111 Name : Roxi