Encapsulation
Objective
In this lab, we will demonstrate Encapsulation in the Java language. By the end of this lab, learners will be able to use Encapsulation.
Introduction to Encapsulation in Java
Encapsulation refers to hiding the class variable from other classes and giving access to them only through methods (setters and getters).
Encapsulation in Java means binding the data (variables) with the code (methods – setters and getters). The below diagram depicts Encapsulation in Java.
💡 Points of the above diagram:
Class Variables (in the example: height, weight, and bmi) are declared private; hence, they are not visible to other classes.
For each variable, there is a setter and getter method, which sets a value to the variable and gets the variable's value, respectively.
Example: For variable height, setter method is setHeight() and getter method is getHeight().
Setter and Getter methods are public; hence, they are visible to other classes.
A Program Example
Create a class named HumanBeing with two constructors: class variables (weight, height, and bmi) and setter and getter methods.
Create a class named EncapsulationExample, with a main() method.
Run/compile your Code,
Output
Person has 68.0 kgs and is 1.65 meters in height, which results in BMI of 24.977045
Last updated