Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Java Jdk7 Encapsulation in Java 7

Related Tutorials


 
 

Share on Google+Share on Google+

Encapsulation in Java 7

Advertisement
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
Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: December 13, 2012

Related Tutorials

Discuss: Encapsulation in Java 7  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:1
seema
March 27, 2013
java

i want to code of calculator in java awt.
DMCA.com