Encapsulation Program in Java for Best Practice
Here, we have listed the top 5 encapsulation program in Java for the best practice with step by step explanation. These encapsulation programming questions are very important for any company interview.
In the previous tutorial, we have learned about encapsulation, data hiding, and tightly encapsulated class in java with realtime example programs.
If you have any doubts related to concepts of encapsulation, I will recommend you first visit the encapsulation tutorial. The link is given here: Encapsulation in Java with Realtime Examples
Let’s take an example program where we will set one field as private in the class Number. So, the field can be accessed only within the class and no one can access it from outside the class.
After that, we will use public setter and getter methods to set and read the value of the variable or field.
By doing this, we are hiding the field and providing its implementation from outside the class. This programming mechanism is called Encapsulation in Java.
It helps to bind the data (variables) and code (methods) together with them. For example, a class is a good example of encapsulation because if we write variables and methods inside the class, the class binds them together.
Program code 1:
Step 1: Create a package named 'numberTest' and make a class 'Number'.
package encapsulationTest;
public class Number
{
// Step 2: Declare field/variable as private.
private int y;
// Step 3: Create a public getter method for the private variable.
public int get() {
return y;
}
// Step 4: Create a public setter method for the private variable and declare the parameter.
public void set(int y) {
this.y = y;
}
}
// Step4: Create another class EncapTest.
public class Encaptest {
public static void main(String[] args)
{
// Step 6: Create an object of class Number using the new keyword.
Number n = new number(); // Here, n is a reference variable of Number and pointing to the object of class Number.
// Step 7: Now call setter method and set value of the variable.
n.set(6);
// Step 8: Call getter method to read the value of variable.
int num = n.get();
// Step 9: Print the output.
System.out.println(num);
}
}
Output: 6
In the preceding example program, the variable y is made private. This variable can be accessed and manipulated only using set() and get() methods.
Thus, we can say that here the variable y and the functions get() and set() are bonded together in a class that represents Encapsulation.
Common mistakes while implementing Getter and Setter methods:
Consider the above code snippet, if the variable y is declared as public then methods can be called and used directly using dot (.) operator from anywhere outside the class and making the setter and getter methods useless.
So, we always declare more restrictive access modifiers such as protected and private.
For example:
protected String name;
private int num;
Now follow all the above steps to make the coding snippet of Encapsulation easy.
Let us understand another example program. In this example program, we will make a class ‘Rectangle’ and declare the variable length and breadth as private. One Constructor will be used for initializing the value of variables.
When an object is created, the constructor will be called and the default value of the instance variables will be assigned.
Program code 2:
Package encapsulationTest;
public class Rectangle
{
// Declare instance variables as private in the class.
private int length;
private int breadth;
// Declare a constructor Rectangle and define parameters of constructor.
Rectangle(int length, int breadth)
{
this.length = length;
this.breadth = breadth;
}
// Create a getter method for each private variable.
public int getLength()
{
return length;
}
public int getBreadth()
{
return breadth;
}
// Create a setter method for each private variable and define the parameter.
public void setLength(int length)
{
this.length = length;
}
public void setBreadth(int breadth)
{
this.breadth = breadth;
}
}
Now create another new class ‘RectangleTest’ and follow all the steps as explained in the above program.
package encapsulationTest;
public class RectangleTest
{
public static void main(String[] args)
{
// Create an object of class Rectangle and assign values of the parameter used in constructor.
Rectangle rt = new Rectangle(20,30);
// Call getter method to read value of variable because we cannot read the value directly due to privacy.
int lth = rt.getLength();
int bth = rt.getBreadth();
// Calculate area of the rectangle and print it on the console.
int Area = lth * bth;
System.out.println("Area: " +Area);
// Let's update the new value of variable using setter method.
rt.setLength(50);
rt.setBreadth(60);
// Call getter method to read the updated value.
int ln = rt.getLength();
int br = rt.getBreadth();
int newArea = ln * br;
System.out.println("New area: " +newArea);
}
}
Output: Area: 600 New area: 3000
Program code 3:
In this example program, we are creating a class Student and declare variables stdName, stdRollNo, and stdId as private. Look at the following source code to understand better.
package encapsulationTest;
public class Student
{
// Step 1: Declare variables private in the class.
private String stdName; // private field.
private int stdRollNo;
private int stdId;
// Step 2: Apply public getter method for each private vairable in the class.
public String getStdName()
{
return stdName;
}
public int getStdRollNo()
{
return stdRollNo;
}
public int getStdId()
{
return stdId:
}
// Step 3: Apply the public setter method for each private variable in the class.
public void setStdName(String name)
{
stdName = name;
}
public void setStdRollNo(int rollNo)
{
stdRollNo = rollNo;
}
public void setId(int id)
{
stdId = id;
}
}
public class EncapTest {
public static void main(String[][] args)
{
// Step 4: Create the object of class Student by using new keyword.
Student obj = new Student(); // Here, obj is reference variable of class Student and pointing to objects of class Student.
// Step 5: Call setter method and set the value of variables.
obj.setStdName("Kiran");
obj.setStdRollNo(4);
obj.setStdId(12345);
// Step 6: Call getter method to read the value of variables and print it on console.
System.out.println("Student's Name: " +obj.getStdName());
System.out.println("Student's Roll no.: " +obj.getStdRollNo());
System.out.println("Student's Id: " +obj.getStdId());
}
}
Output: Student's Name: Kiran Student's Roll no.: 4 Student's Id: 12345
If we do not define setter method in the class, fields can be made read-only. Let’s take an example program where we will create a class ‘Player’ in which all the fields are declared as private.
A constructor will be declared for initializing the parameters because we will not declare the setter method in the class. So, we will use constructor to initialize the value of variables.
Program code 4:
package encapsulationTest;
public class Player
{
private String pName;
private int pAge;
private String gameType;
// Create a constructor and initialize the three parameters pName, pAge, and gameType.
public Player(String pName, int pAge, String gameType)
{
this.pName = pName;
this.pAge = pAge;
this.gameTypte = gameType;
}
public String getPName()
{
return pName;
}
public int getPAge()
{
return pAge;
}
public String getGameType()
{
return gameType;
}
}
public class PlayerTest {
public static void main(String[] args) {
Player ply = new Player("Sachin", 40, "Cricket");
String plyName = ply.getPName();
int plyAge = ply.getPAge();
String plyGameType = ply.getGameType;
System.out.println("Player's Name: " +plyName);
System.out.println("Player's Age: " +plyAge);
System.out.println("Player's Gametype: " +plyGameType);
}
}
Output: Player's Name: Sachin Player's Age: 40 Player's Gametype: Cricket
If we do not define the getter method in the class then fields can be made write-only.
Let’s take an example program where we will only define setter method in the class to make write-only. We will not define getter method and constructor because we can send direct values of the parameter using constructor.
Program code 5:
package encapsulationTest;
public class Student
{
private String name;
private int phyMarks;
private int chemMarks;
private int bioMarks;
public void setName(String name)
{
this.name = name;
}
public void setPhyMarks(int phyMarks)
{
this.phyMarks = phyMarks;
}
public void setChemMarks(int chemMarks)
{
this.chemMarks = chemMarks;
}
public void setBioMarks(int bioMarks)
{
this.bioMarks = bioMarks;
}
void marksRead()
{
System.out.println("Student's Name: " +name);
System.out.println("Marks in Physics: " +phyMarks);
System.out.println("Marks in Chemistry: " +chemMarks);
System.out.println("Marks in Biology: " +bioMarks);
int Totalmarks = phyMarks + chemMarks + bioMarks;
float percentage = (Totalmarks * 100)/300;
System.out.println("Percentage of PCB: " +percentage);
}
}
public class StudentMarks {
public static void main(String[] args)
{
Student st = new Student();
st.setName("Vivek");
st.setPhyMarks(85);
st.setChemMarks(75);
st.setBioMarks(90);
st.marksRead();
}
}
Output: Student's Name: Vivek Marks in Physics: 85 Marks in Chemistry: 75 Marks in Biology: 90 Percentage of PCB: 83.33
In this tutorial, you have practiced all types of encapsulation program in Java. I hope that you will have understood the encapsulation concepts in Java with the help of practiced example programs.
Recommended Tutorial for Interview