Module 17: Scope and Encapsulation


Objectives

 

By the end of this module, you will be able to:

 


Global variables

 

Consider the following program:

 

In-Class Exercise 1: Execute the above program. What does it print?
 

Let us point out a few things:

 

In-Class Exercise 2: Define another global variable, an int, and two new methods. Then use (and modify) the new variable in both methods. Demonstrate its use by printing the values of the variable both before and after modification.
 

Why are globals useful? Let's look at an example:

 

In-Class Exercise 3: Achieve the same results without global variables. Instead of computeBounds, you can define one method each for the min and max of x values, and one method each for the min and max of y values.
 


Variable shadowing and scope

 

Consider this program:

  • Consider the method foo:

    The local definition of a variable with the same name y shadows the name of the global.

  • Something similar happens with the method bar:

    Thus, parameter variables shadow (obscure) global variables of the same name.

 

In general, variables can be defined in any block of code:

  • Here, the m and n in main refer to the global m and n

  • However, the m in foo is a local variable that shadows the global one:

  • The scope of a variable is the block of code that can access a variable.

  • The scope of the global variable m is any method inside the class.

  • Similarly, one can see the scope of the other variables in method foo, for example m:

  • And the others:

 

Now consider this example:

 

In-Class Exercise 4: What gets printed out? The value 1 repeatedly or increasing values of m?
 


Packaging and encapsulation

 

Consider the following program:

  • Here, we see that there is an array and a bunch of methods that "do things" with the array.

  • Now, the methods appear to be of general use to a variety of arrays, and could be useful in the future.

  • Suppose we were to "package" these useful methods into a class called ArrayTool as follows:

  • Then, these could be used in the future by any program in the same directory as ArrayTool, e.g.,

  • This type of packaging is called encapsulation.
    • Related code can be together.
    • Other programs need not know the details, they can just use (i.e., call) the methods in the class.

  • Such encapsulation and re-use is a key part of how efficiencies are realized in software development.

  • When you learn about objects and data structures in later courses, you will see many more such ideas.
 

In-Class Exercise 5: Add a new useful method to ArrayTool above and use it in a new application.


© 2011, Rahul Simha