WC - Scope and Access (Lesson)

APCompSci_LessonTopBanner.png

Scope and Access

Introduction

Did you know that the scope of a boat on a buoy or anchor is the distance the boat can drift in a circle around the anchor or buoy? It is relative to the length of rope that ties the boat and the depth of the water. Variables in code have scope too.

boats 

 

Scope

Variables only exist within the braces where they are defined. For example, in the computeArea method, the variable area only exists in that method. If you were to use area somewhere outside that method without redefining it, it would not work. This does not mean, however, that the value for area is not returned to the calling program of the computeArea method.

When variables are declared within a method or constructor they will only exist within that constructor and method.

In the computeArea method in the Triangle class, area is a local variable:

public double computeArea ()
{
double area;
area = .5*base*height;
return area;
} 

Local Variables

The variable area is an example of a local variable since it is only available within the computeArea method. Variables base and height, however, are instance variables since they are declared at the start of the class and are used throughout.

Local variables may only be used within the constructor or method where they are declared. They cannot be declared as public or private.

When there is a local variable with the same name as an instance variable, the variable name will refer to the local variable instead of the instance variable. This can make code very confusing for programmers to read. To make it easier, it is best to create unique variable names. If it is necessary to use the same name, the keyword, this, can be used. Within a non-static method or constructor, the keyword this is a reference to the current object – the object whose method or constructor is being called.

public void setBase (double base)
{
this.base = base;
} 

In the above code segment, the variable base is used for two different variables. The keyword, this, is used in front of the reference variable base to reference the current object. The other base is the parameter variable. While this is legal code, it is much better to create unique variable names so that other programmers can easily read your code.

Objects and Classes Review

 

Self-Assessment Content

Writing Classes Test Review

  1. Go to AP Classroom Links to an external site..
  2. Complete the Unit 5 Progress Check(s)

APCompSci_LessonBottomBanner.pngIMAGES CREATED BY GAVS