Module 8: Scope and Encapsulation


Objectives

 

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

 

8.0 Audio:
 


8.0    Global variables

 

Consider the following program:

 

8.1 Exercise: Execute the above program. What does it print?
 

Let us point out a few things:

  • The variable x is declared outside any of the methods, including main:

  • It is accessible in any method defined in the class:

  • Such a variable is called a global variable.
           ⇒ It's global to all the methods in the class.
 

8.2 Exercise: In MyScopeExample.java, add 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:

  • Suppose we have the following data in the file file.data.
    5
    2.0  1.0
    0.5  3.0
    3.1  5.2
    4.0  3.6
    5.0  0.5
       
    The integer on the first line is the number of points. Then, each line has one (x,y) pair.

  • Goal: read the points and then compute the minimum, maximum of the x and y values.

  • Here's the program:

  • Here, we've conveniently used a single set of globals that is accessed by multiple methods.

  • If we did NOT use globals, we would have to use return values and parameters for all of those methods to "do things" to the array.
 

8.3 Exercise: To see what it's like to live without global variables, in MyPointsExample.java, 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.
 

8.4 Audio:
 


8.1    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:

 

8.5 Exercise: What gets printed out? The value 2 repeatedly or increasing values of m?
 

8.6 Audio:
 


8.2    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.
 

8.7 Exercise: Add a new useful method to ArrayTool above and use it in a new application.
 


8.3    When things go wrong

 

In each of the exercises below, first try to identify the compiler or logical error just by reading. Then implement to check your answer.
 

8.8 Exercise:

public class ScopeErrors {

    static int c;

    public static void main (String[] argv)
    {
	addAndThenSquare (3, 4);
	System.out.println (d);
    }

    static int addAndThenSquare (int a, int b)
    {
        c = a + b;
	int d = c * c;
	return d;
    }

}
   
 

8.9 Exercise:

public class ScopeErrors2 {

    static int c;

    public static void main (String[] argv)
    {
	addAndThenSquare (3, 4);
	System.out.println (c);
    }

    static void addAndThenSquare (int a, int b)
    {
        int d = a + b;
	int c = d * d;
    }

}
   
 

8.10 Exercise:

public class ScopeErrors3 {

    static int[] A;
    static int sum;

    public static void main (String[] argv)
    {
	int[] A = {1, 2, 3};
	addThemUp (A);
    }

    static void addThemUp (int[] A)
    {
	sum = 0;
	for (int i=0; i<A.length; i++) {
	    sum = sum + A[i];
	}
    }

}
   
 

8.11 Exercise:

public class ScopeErrors4 {

    public static void main (String[] argv)
    {
	int[] A = {1, 3, 5, 7, 9};
	int a = 3;
	for (int i=0; i<A.length; i++) {
	    if (A[i] == a) {
                // Found.
		break;
	    }
	}
	System.out.println ("Found at position " + i);
    }

}
   
 

8.12 Exercise:

public class ScopeErrors5 {

    static int i = 0;

    public static void main (String[] argv)
    {
	int[] A = {1, 3, 5, 7, 9};
	for (int i=0; i<A.length; i++) {
	    if (A[i] == 5) {
                // Found.
		break;
	    }
	}
	System.out.println ("Found at position " + i);
    }

}
   
 


8.4    Meta

 

8.13 Exercise: In HiddenMessage.java compile and execute the following program:

	int[] B = {87, 101, 108, 108, 32, 100, 111, 110, 101, 33};
	for (int i=0; i<B.length; i++) {
	    System.out.print ( (char)B[i] );
	}
	System.out.println ();
   
Exactly. Just think about the volume of material covered so far in units 0 and 1:
  • The "guts" of programming: variables, loops, conditionals, arrays, methods.

  • A few key additional important aspects: input/output, scope, working with numbers, letters, chars.

  • Problem-solving with programming.
Along with these concepts, you have put them into practice by writing lots of little programs, and a few bigger ones in the assignments.

Consider wrapping up the next assignment, then taking a break and rewarding yourself. We're in the home stretch now. Well done!
 

8.14 Audio:




On to Assignment 2



© 2017, Rahul Simha