Encapsulation java code Example

Last Updated On Saturday 4th Jun 2022


In Java, class is an example of Encapsulation. A class wraps code (method) and data(variables) together.

  • This concept ensures that data members of a class are always hidden from other classes.
  • We can only access those data members using the methods.
  • Encapsulation is also known as data-hiding as it prevents data from being accessed by the code outside the class.
	public class book {
    private String name;
    private String authorName;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAuthorName() {
        return authorName;
    }

    public void setAuthorName(String authorName) {
        this.authorName = authorName;
    }
}
	

Advantages of Encapsulation

  • We can make read-only and write-only classes using Encapsulation.
  • We can achieve data hiding.
  • The encapsulated classes are better for unit testing.
  • It is easy and fast.
  • We have control over data.