Introduction to Encapsulation - Part 1 Tutorial

This is part one of a two part tutorial on the concept of encapsulation. It is almost impossible to explain the concept of encapsulation with just wording alone. You must first understand the problem that encapsulation resolves. By the end of part two, you should have a good grasp of what encapsulation is.
An instance variable is a variable declared in a class that has a separate copy (value) for each object created. In my Instance Variable Tutorial, we saw how we could directly set the values of the instance variables for each object we created. Now what do we do if we want to control what values can be stored in an instance variable? We can use a setter method to set the value of an instance variable. We can get the value of an instance variable by using a getter method. Becoming familiar with getter and setter methods is key to understanding the concept of encapsulation.

Setter methods

class Box {
      int length = 0; // instance variable - we can change its value directly from the object instance
      int height = 0; // height could be directly set to a negative value - that's not good!
      int width = 0;

      // I will create a setter method to set the height
      boolean setHeight (int heightParam) {
            if (heightParam >= 1) {
                  height = heightParam;
                  return true;
            } else {
                  return false;
            }
      }

      int calculateVolume() {
            return length * width * height;
      }
}

Getter methods

Getter methods will be discussed in detail in part 2
class Box {
      int length = 0; // instance variable - we can change its value directly from the object instance
      int height = 0; // we can get this value directly now, in part 2 we won't
      int width = 0;

      // I will create a getter method to get the height
      // Who knows why ... we might want to know if a box is too tall to fit on a shelf
      int getHeight () {
            return height;
      }

      int calculateVolume() {
            return length * width * height;
      }
}



Open the command prompt (CMD - see the Getting Started ) and type in the following commands.

C:\Windows\System32>cd \
C:\>md Java
C:\>cd Java
C:\Java>
C:\Java>md EncapsulationOne
C:\Java>cd EncapsulationOne
C:\Java\EncapsulationOne>Notepad Box.java

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.


class Box {
    int length = 0; // instance variable - every Box object will have its own "instance" (copy) of this variable
    int height = 0; // height could be directly set to a negative value - that's not good!
    int width = 0; // width could be directly set to a negative value - that's not good!

    boolean setLength (int lengthParam) {
        if (lengthParam >= 1) {
            length = lengthParam;
            return true;
        } else {
            return false;
        }
    }

    boolean setHeight (int heightParam) {
        if (heightParam >= 1) {
            height = heightParam;
            return true;
        } else {
            return false;
        }
    }

    boolean setWidth (int widthParam) {
        if (widthParam >= 1) {
            width = widthParam;
            return true;
        } else {
            return false;
        }
    }

    // I will create a getter method to get the height
    // Who knows why ... we might want to know if a box is too tall to fit on a shelf
    int getHeight () {
        return height;
    }

    // create a method to get the volume of the box
    int calculateVolume() {
       return (length * height * width);	
    }
}

Now switch back to the command prompt (CMD) and type in javac Box.java and press Enter.
Switch back to the CMD prompt and type in the following command.

C:\Windows\System32>cd \
C:\Java\EncapsulationOne>Notepad EncapsulationOne.java


Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.


class EncapsulationOne {
    public static void main(String args[]) {
	
        Box b = new Box(); // single statement - declare reference variable and allocate new Box object
		
        b.length = 10; // directly set the instance variable
        b.height = -2; // directly set the instance variable to value we didn't expect
        b.width = 5; // directly set the instance variable

        System.out.println("The volume of our box is: " + b.calculateVolume());
        System.out.println("The height of our box is: " + b.height);
    }
}

Now switch back to the command prompt (CMD) and type in javac EncapsulationOne.java and press Enter.
Now type in java EncapsulationOne and press Enter.


C:\Java\EncapsulationOne>javac EncapsulationOne.java
C:\Java\EncapsulationOne>java EncapsulationOne
The volume of our box is: -100
The height of our box is: -2

That's not good! I will now use setter methods to set the length, width, and height. Overwrite the following code into Notepad and be sure to save the file when you are done.


class EncapsulationOne {
    public static void main(String args[]) {	
        Box b = new Box(); // single statement - declare reference variable and allocate new Box object

        //b.length = 10; // directly set the instance variable
        //b.height = -2; // directly set the instance variable to value we didn't expect
        //b.width = 5; // directly set the instance variable

        if (b.setLength(10) && b.setHeight(-2) && b.setWidth(5)) {
            System.out.println("The volume of our box is: " + b.calculateVolume());
            System.out.println("The height of our box is: " + b.getHeight());
        } else {
            System.out.println("Unexpected value in one of the dimension arguments.");
        }
    }
}

Now switch back to the command prompt (CMD) and type in javac EncapsulationOne.java and press Enter.
Now type in java EncapsulationOne and press Enter.


C:\Java\EncapsulationOne>javac EncapsulationOne.java
C:\Java\EncapsulationOne>java EncapsulationOne
Unexpected value in one of the dimension arguments.

Change the setHeight(-2) to setHeight(2) and recompile and run.


C:\Java\EncapsulationOne>javac EncapsulationOne.java
C:\Java\EncapsulationOne>java EncapsulationOne
The volume of our box is: 100
The height of our box is: 2


Final thoughts

At this point there is nothing that prevents a programmer from directly accessing the instance variables. They are not forced to use the new setter methods that we just created. So how do we make the instance variables not accessible? Stay tuned for part 2 of this tutorial.


Tutorials