Let’s say you share your new Box class with all of your friends.
Listing 1 - Box.java (version 4)
public class Box
{
int length;
int width;
int height;
int volume;
void computeVolume()
{
volume = length * width * height;
}
}
One of your friends tells you that your class doesn’t work. They tried computing the volume of a box with dimensions 5 X 5 X 4 and got 101 instead of 100. You ask to see the main program, and find the following:
Box b1 = new Box();
b1.length = 5;
b1.width = 5;
b1.height = 4;
b1.computeVolume();
b1.volume++; // What’s this?
System.out.println(“volume = “ + b1.volume); // Prints volume = 101
Your friend has modified the volume field in the Box object even though it was unnecessary. Not a problem, you point out the error, and after removing the erroneous statement, the program works fine. But what if there were millions of users of your class? You need a way to prevent errors like the one above from happening. This is done using encapsulation.
Section 1 - Encapsulation Defined
Copyright ©2017 by Ralph Lecessi Incorporated. All rights reserved.