Once you click post assignment, learners in the selected class will immediately be able to see and complete this assignment
Back to Classroom
Encapsulation
Java Basics Course
Engineers From These Top Companies and Universities Trust EXLskills
1M+ Professionals | 100+ Institutions
This is the EXLskills free and open-source Java Basics Course. It guides learners via explanation, demonstration, and thorough practice, from no more than a basic understanding of Java, to a moderate level of essential coding proficiency.
-->
Is this course FREE?
Yes, this a 100% free course that you can contribute to on GitHub here!
Encapsulation is the idea of withholding the details of an object from other parts of the program while allowing its use. The object is only used through its access methods, which are carefully written to keep the object consistent and secure. We use the Java reserved word private to guarantee other classes have no access to the member of a certain class. Let's see how a private variable has access methods that allow it to be viewed.
EncapsulationExample.java
package exlcode;
public class EncapsulationExample {
public static void main(String[] args) {
EncapsulationTest encapsulationTest = new EncapsulationTest();
System.out.println(encapsulationTest.getVariableOne());
}
}
EncapsulationTest.java
package exlcode;
public class EncapsulationTest {
private String exampleVariableOne = "Hello World!";
// private variables can be accessible through
// public methods
public String getVariableOne() {
return exampleVariableOne;
}
}
The EncapsulationTest class consists of two main members, the private variable exampleVariableOne and the method getVariableOne(). This is a "getter" method, which returns the value of a private member of the class. This method ensures exampleVariableOne will never be in danger of being changed or manipulated even though it is visible through the getter method. This is one example of how encapsulation works. It's a concept that will help you avoid unwanted errors when writing big programs.