Articles

How encapsulation is achieved in java?

How encapsulation is achieved in java?


Encapsulation is the process of wrapping up of data and function into a single unit called class.

Encapsulation helps in hiding the data from the outside world so it is also known as data hiding.

 

Lets see how we can acheive encapsulation in java.

 

To achieve encapsulation in java

  • declare the variable you want to hide as private.
  • use getter and setters to allow access to the private variables in java.

Lets see the example:

public class Subjects {

	private String subjectName;
	private int subjectID;	
	
	public String getSubjectName() {
		return subjectName;
	}

	public void setSubjectName(String subjectName) {
		this.subjectName = subjectName;
	}

	public int getSubjectID() {
		return subjectID;
	}

	public void setSubjectID(int subjectID) {
		this.subjectID = subjectID;
	}

}

From the above code we can figure out:

  • variables subjectName and subjectId are declared as private. So it cannot be directly accessed by outside classes.
  • We have provided getter and setter methods (eg. getSubjectName(), setSubjectName) as part setting data as well as getting data for these variables.

In this way we can implement encapsulation and data hiding in java.


Java Interview Questions

Would you like to see your article here on tutorialsinhand. Join Write4Us program by tutorialsinhand.com

About the Author
Sonu Pandit
Technology geek, loves to write and share knowledge with the world. Having 10+ years of IT experience. B.Tech in Computer Science & Engineering
Page Views :    Published Date : Jul 13,2020  
Please Share this page

Related Articles

Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!