Home Java Javatutorial Encapsulation in Java
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

Encapsulation in Java

Advertisement
Encapsulation along with Inheritance, Polymorphism, and Abstraction are the four concepts of Object Oriented Programming (OOPs). Encapsulation in Java is the technique of binding or wrapping the data and the codes in a class private and provides access to them by public methods. Encapsulation is a type of data hiding where a code and data declared private cannot be accessed by any other code outside the class.

Encapsulation along with Inheritance, Polymorphism, and Abstraction are the four concepts of Object Oriented Programming (OOPs). Encapsulation in Java is the technique of binding or wrapping the data and the codes in a class private and provides access to them by public methods.

Encapsulation is a type of data hiding where a code and data declared private cannot be accessed by any other code outside the class. Interface controls the data and code access.

In other words, it is the ability of an object to be a container for related data variables and methods. Encapsulation gives maintainability, flexibility and extensibility to the code.

With the use of Encapsulation, programmer can modify an implemented code without changing it for others who use the code.

Encapsulation points to remember:

  • It helps in separating the states of an object from its behavior.
  • Unwanted data or code that is not required by an object is kept hidden.
  • Information hiding does not allow the accessed to any other code outside the class and thus provides security.
Example of Encapsulation in Java:
package Enum;

public class StudentDetails {
	 private String name;
	 private String address;
     private String mobileNo;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public String getMobileNo() {
		return mobileNo;
	}
	public void setMobileNo(String mobileNo) {
		this.mobileNo = mobileNo;
	}
	

}

package Enum;

public class StudentDetailsmain {
	public static void main(String[] args) {
		StudentDetails details = new StudentDetails();
		 details.setName("Rose");
		 details.setAddress("Delhi G-25");
		 details.setMobileNo("82855598");
		 System.out.println("name: "+details.getName()+ "Address:" +details.getAddress()+ "MobileNo:" +details.getMobileNo());
		
	}
	

}
Advertisement

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: April 26, 2013

Ask Questions?    Discuss: Encapsulation in Java  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
DMCA.com