Core Java - SPLessons

Encapsulation in Java

Chapter 23

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Encapsulation in Java

Encapsulation in Java

shape Description

Encapsulation in Java, Encapsulation is a process of protecting the members of the class. Java is completely encapsulated body which protects a member by using access specifiers. Best example is Java Bean Class. Developing a Java class with the private fields and providing access to the private fields using getters and setter method is known as a Java Bean Class.
Encapsulation in Java, Constructor of a Bean Class must be public and also setters and setters must be public to protect the members of the class, whatever the members have to be developed, those members should be developed either inside class body or inside an interface body. For a constructor , four Access Specifiers can be used as follows.

Advantages of Encapsulation in Java


shape Example

Encapsulation in Java, To understand the encapsulate concept here developer is going to take two classes by the name Student and Test. In Student developer used getName() method and through the Test class code has been compiled.
Student.java

public class Student{  
private String name;  
   
public String getName(){  
return name;  
}  
public void setName(String name){  
this.name=name; 
}  
}  

Where created getName() method and it will be retrieved by Test class.

public String getName()

Where setName() is used to set the name.

public void setName(String name)

Test.java

class Test{  
public static void main(String[] args){  
Student s=new Student();  
s.setName("SPLESSONS");  
System.out.println(s.getName());  
}  
}  

Where created an object to the previous class Student, through the object name has been given.

Student s=new Student();  
s.setName("SPLESSONS");  
System.out.println(s.getName());  

Output:
When compile the code following is the result will be displayed.

SPLESSONS

Abstraction vs Encapsulation in Java

Encapsulation in Java is represented using private, package-private and protected access modifier. It wraps the method data, variables and codes within a class into a single entity. The class and methods outside the wrapper cannot access the code and data defined under the wrapper. In encapsulation object becomes a container for related data variables and methods.

Abstraction in Java is represented by Interface, Abstract class, Abstract methods using “abstract” keyword. It hides certain details of the object that are not important and display that are essential.
For more detailed overview on abstraction click here .
For more detailed overview on encapsulation click here .
For more detailed overview on access modifiers click here .


Summary

shape Key Points

  • Encapsulation in Java concept, setter and getter methods are used to make the class as read-only-write-only.
  • Encapsulation in Java – Encapsulation provides the control over the data.