Introduction to Encapsulation - Part 2 Tutorial

In part one I introduced the concept of setter and getter methods, these methods are also known as mutator (setter) and accessor (getter) methods. Also in part one I left you hanging on how we can prevent the direct usage of our instance variables. We can control the access to our instance variables using access modifiers. The topic of access modifiers is quite extensive and there are many rules that are way beyond the scope of this tutorial. I will be covering them in detail in future tutorials, but for now I will introduce you to the access modifier private and how it affects instance variables. The access modifier private must be placed before the type when declaring an instance variable. It works like this:
(access modifier) (type) (instance variable) (;)
private int width;

When we mark a variable as private, only the members inside of the class body (the area between the braces) have access to it. At that point a reference variable can no longer access the variable directly by using the dot operator. The only way to set and get the value of the instance variable is via the setter and getter methods. We have created a sort of capsule to protect the instance variables from direct manipulation that could produce unexpected results, hence the term encapsulation.



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 EncapsulationTwo
C:\Java>cd EncapsulationTwo
C:\Java\EncapsulationTwo>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 {
    private int length = 0; // private access modifier must come before the data type
    private int height = 0; // only the methods in this Box class can access the scope of these variables 
    private int width = 0; // private instance variables cannot be accessed directly outside of this class

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

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

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

    // 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\EncapsulationTwo>Notepad EncapsulationTwo.java

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


class EncapsulationTwo {
    public static void main(String args[]) {
	
        Box b = new Box(); // single statement - declare reference variable and allocate new Box object
		
        //b.length = 10; // we can no longer set the value of the instance variable directly!

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

    }
}

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


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

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


C:\Java\EncapsulationTwo>javac EncapsulationTwo.java
C:\Java\EncapsulationTwo>java EncapsulationTwo
The length of our box is: 10
The height of our box is: 2
The width of our box is: 5
The volume of our box is: 100


Final thoughts

There are three key principles of Object-Oriented programming: encapsulation, polymorphism, and inheritance. Don't worry about polymorphism and inheritance yet, I will explain those concepts in future tutorials. When an instance variable is declared private, it cannot be accessed outside of the class, therefore it is protected within a "capsule" inside the class. Encapsulation is the principle of restricting access to the variables (fields) using setter and getter methods.


Tutorials