Skip to main content
Logo image

Section 9.3 Scope and Access

The scope of a variable is defined as where a variable is accessible or can be used. The scope is determined by where you declare the variable when you write your programs. When you declare a variable, look for the closest enclosing curly braces ({}) – this is its scope.

Subsection 9.3.1 Class Methods vs. Instance Methods

In lessons 1.9 and 1.10, we learned how to call class methods (also called static methods). Class methods are called using the class name followed by the dot (.) operator and the method name, example, Math.sqrt(25); calls the sqrt method in the Math class to find the square root of 25. Class methods use the keyword static in their method signature. They do not access or change the attributes of an object.
In this lesson, we will learn more about instance methods which are always called using an object of the class. They are not static methods. They access and change the attributes of the object they are called on, for example yertle.forward() changes the Turtle object yertle’s position.
The following flowchart shows the difference between calling class (static) methods and instance methods. Static methods are called using the class name, for example, Math.sqrt(25);. Instance methods are called using an object of the class, for example, yertle.forward();. Traditionally, class names are capitalized, and object variables are lowercase.
Calling static vs. instance methods
Figure 9.3.1. Calling static vs. instance methods

Subsection 9.3.2 Class Methods

Class methods belong to the class and not to any object of the class. They are called with the class name and the dot operator, like ClassName.methodName();, for example the Math methods like Math.random();. There is only one copy of a class variable or method for the whole class. For example, the main method is a class (static) method because there should only be 1 main method. If the method is in the same class, you can call it with or without the class name from other static methods in the class: Classname.methodName(); or staticMethodName(); or even with an object of the class: objectName.methodName();.
// Calling class methods
// ClassName.methodName();
int x = Math.sqrt(9);

 // If the method is in the same class,
 // you can call it with or without the class name
 // from other static methods in the class
 ClassName.methodName();
 methodName();
Let’s revisit the following flowchart to compare three different ways of calling methods. Class (static) methods are called using the class name. Instance methods can only be called using an object of the class. If you are calling the instance method from the main method or from another class, you must first create an object of that class and then call its methods using object.methodName(). If you are calling the method from within the same class, you can just call the method using methodName() which will refer to the current object.
Comparing method calls to static and instance methods
Figure 9.3.2. Comparing Method Calls to Static and Instance Methods
When writing class methods, they can be public or private. The static keyword is placed right after the public/private modifier and right before the type of variables and methods in their declarations.
public class ClassName
{
  // static class variable
  public static type variableName;

  // static class method
  public static returnType methodName(parameters)
  {
        // implementation not shown
  }
}
Class (static) methods can access or change the values of class (static) variables and can call other class (static) methods. However, they cannot access or change the values of (non-static) instance variables or call (nont-static) instance methods without being passed an instance of the class via a parameter. For example, the main method which is static can call other static methods directly with or without the classname, but it cannot call instance methods without first creating an object. Try this below to see β€œnon-static variable or method cannot be referenced from a static context” errors.

Activity 9.3.1.

Note that the static method printStatic has errors in it because it cannot access the instance variables and methods. Fix the printStatic method by giving it the Person object as a parameter and using this object to call its instance variables and methods. Also fix the method call to printStatic in main to pass in the object as an argument.
This example also shows how instance methods easily share data variables without the need for parameters. Whereas, static methods cannot directly access the instance methods. They are often used for utility methods, like Math operations, that do not need access to the instance variables of an object.

Subsection 9.3.3 Class Variables

Class variables belong to the class, with all objects of a class sharing a single copy of the class variable. Class variables are designated with the static keyword before the variable type. Class variables that are designated public are accessed outside of the class by using the class name and the dot operator, since they are associated with a class, not objects of a class.
In the following class Person, there is a static variable called personCounter that is incremented each time the Person constructor is called to initialize a new Person object. The static method printCounter prints out its value. You can also watch how it works in the Java visualizer by clicking the CodeLens button below.

Activity 9.3.2.

What will the following code print out? Try adding another Person object and see what happens. Try the CodeLens button to run the code step by step.
Another common use for static variables is the keep track of a minimum or maximum value or an average of the values in a collection of objects.

Activity 9.3.3.

Consider the class Temperature below which has a static variable. What is the output of the main method below?
public class Temperature {
    private double temperature;
    public static double maxTemp = 0;

    public Temperature(double t) {
        temperature = t;
        if (t > maxTemp) {
            maxTemp = t;
        }
    }

    public static void main(String[] args) {
        Temperature t1 = new Temperature(75);
        Temperature t2 = new Temperature(100);
        Temperature t3 = new Temperature(65);
        System.out.println("Max Temp: " + Temperature.maxTemp);
    }
}
  • Max Temp: 0
  • maxTemp is changed in each call to the Temperature() constructor.
  • There is a compiler error because the static variable maxTemp cannot be used inside a non-static constructor.
  • Non-static methods and constructors can use any instance or static variables in the class.
  • Max Temp: 100
  • Yes, maxTemp is initialized to 0 and then changed to 75 and then 100 by the constructor calls.
  • Max Temp: 75
  • maxTemp will be changed to 100 by the second constructor call since 100 > 75.
  • Max Temp: 65
  • maxTemp will not be changed to 65 by the third constructor call because 67 is not > 100.
You can see this code in action in the Java visualizer.

Activity 9.3.4.

Fix the bugs in the following code. Static methods should only access static variables.

Subsection 9.3.4 final keyword

The keyword final can be used in front of a variable declaration to make it a constant value that cannot be modified. Constants are traditionally capitalized.
final double PI = 3.14

Activity 9.3.5.

Try the following code and notice the syntax error when we try to change the constant PI. Put the comment symbols // in front of that line to remove the error and run it again.

Subsection 9.3.5 Class, Method, and Block Level Scope

Java has 3 levels of scope that correspond to different types of variables:
  • Class Level Scope for instance variables inside a class.
  • Method Level Scope for local variables (including parameter variables) inside a method.
  • Block Level Scope for loop variables and other local variables defined inside of blocks of code with { }.
The image below shows these 3 levels of scope.
Scope Levels
Figure 9.3.3. Class, Method, and Block Level Scope

Activity 9.3.6.

Activity 9.3.7.

Subsection 9.3.6 Local Variables

Local variables are variables declared in the headers or bodies of blocks of code. Local variables can only be accessed in the block in which they are declared. Local variables that are declared inside a method are usually declared at the top of the method. These variables can only be used within the method and do not exist outside of the method.
Parameter variables are also considered local variables that only exist for that method or constructor. These variables may only be used within the constructor or method and cannot be declared to be public or private.It’s good practice to declare any variables that are used by just one method as local variables in that method.
Instance variables at class scope are shared by all the methods in the class and can be marked as public or private with respect to their access outside of the class. They have class scope regardless of whether they are public or private.
Another way to look at scope is that a variable’s scope is where it lives and exists. You cannot use the variable in code outside of its scope. The variable does not exist outside of its scope.

Activity 9.3.8.

Try the following code to see that you cannot access the variables outside of their scope levels in the toString() method. Explain to someone sitting next to you why you can’t access these. Try to fix the errors by either using variables that are in scope or moving the variable declarations so that the variables have larger scope.
If 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, as seen below. We’ll see in the next lesson, that we can distinguish between the local variable and the instance variable using the keyword this to refer to this object’s instance variables.

Activity 9.3.9.

In this example, the local variable is used instead of the instance variable of the same name. What will the code print out? Try it with the CodeLens button.

Subsection 9.3.7 Coding Challenge: Debugging

Project 9.3.10.

Debug the following program that has scope violations. You may need to add methods or use methods that are in the class Fraction appropriately. Then, add comments that label the variable declarations as class, method, or block scope.

Subsection 9.3.8 Coding Challenge: Static Song and counter

In SectionΒ 3.1Β Writing methods, we wrote a class with methods to print out the song The Ants Go Marching. Here’s the song with three verses, where the chorus is the last two lines of each verse:
Verse 1:
The ants go marching one by one, hurrah, hurrah
The ants go marching one by one, hurrah, hurrah
The ants go marching one by one
The little one stops to suck a thumb
And they all go marching down to the ground
To get out of the rain, BOOM! BOOM! BOOM! BOOM!

Verse 2:
The ants go marching two by two, hurrah, hurrah
The ants go marching two by two, hurrah, hurrah
The ants go marching two by two
The little one stops to tie a shoe
And they all go marching down to the ground
To get out of the rain, BOOM! BOOM! BOOM! BOOM!

Verse 3:
The ants go marching three by three, hurrah, hurrah
The ants go marching three by three, hurrah, hurrah
The ants go marching three by three
The little one stops to climb a tree
And they all go marching down to the ground
To get out of the rain, BOOM! BOOM! BOOM! BOOM!
Let’s create a class to print out the song with two methods chorus() and verse, where the verse takes two parameters for the numbers and the action. Notice that this is a class where there are no instance variables and we don’t really need to generate multiple objects. With students or pets, it makes sense to have multiple objects. With a class printing out a song, we can just make the methods static and have just one copy of them.
  1. Create a class called Song with two static methods: chorus() and verse(). The chorus method prints out the last two lines of each verse. The verse method takes two parameters, a number and an action, and prints out the verse with the number and action.
  2. Add a public static variable called numVerses to the class that keeps track of the number of verses. Increment this variable in the method verse and print it out at the beginning of the verse.

Project 9.3.11.

This class should print out the The Ants Go Marching Song using two static methods: chorus() and verse(). The chorus method should print out the last two lines of each verse. The verse method should take two parameters, a number and an action, and print out the verse with the number and action. Add a public static variable called numVerses that keeps track of the number of verses. Increment this variable in the method verse and print it out at the beginning of the verse.

Subsection 9.3.9 Summary

  • (AP 3.7.A.1) Class methods cannot access or change the values of instance variables or call instance methods without being passed an instance of the class via a parameter.
  • (AP 3.7.A.2) Class methods can access or change the values of class variables and can call other class methods.
  • (AP 3.7.B.1) Class variables belong to the class, with all objects of a class sharing a single copy of the class variable. Class variables are designated with the static keyword before the variable type.
  • (AP 3.7.B.2) Class variables that are designated public are accessed outside of the class by using the class name and the dot operator, since they are associated with a class, not objects of a class.
  • (AP 3.7.B.3) When a variable is declared final, its value cannot be modified.
  • Scope is defined as where a variable is accessible or can be used.
  • (AP 3.8.A.1) Local variables are variables declared in the headers or bodies of blocks of code. Local variables can only be accessed in the block in which they are declared.
  • (AP 3.8.A.1) Parameters to constructors or methods are also considered local variables. These variables may only be used within the constructor or method and cannot be declared to be public or private.
  • (AP 3.8.A.2) When there is a local variable or parameter with the same name as an instance variable, the variable name will refer to the local variable instead of the instance variable within the body of the constructor or method.

Subsection 9.3.10 AP Practice

Activity 9.3.12.

Consider the following class definitions. Which of the following best explains why the class will not compile?
public class Party {
    private int boxesOfFood;
    private int numOfPeople;

    public Party(int people, int foodBoxes) {
        numOfPeople = people;
        boxesOfFood = foodBoxes;
    }

    public void orderMoreFood(int additionalFoodBoxes) {
        int updatedAmountOfFood = boxesOfFood + additionalFoodBoxes;
        boxesOfFood = updatedAmountOfFood;
    }

    public void eatFoodBoxes(int eatenBoxes) {
        boxesOfFood = updatedAmountOfFood - eatenBoxes;
    }
}
  • The class is missing an accessor method.
  • There is a scope violation.
  • The instance variables boxesOfFood and numOfPeople should be designated public instead of private.
  • There is a scope violation. Instance variables are usually private.
  • The return type for the Party constructor is missing.
  • There is a scope violation. Constructors do not have return types.
  • The variable updatedAmountOfFood is not defined in eatFoodBoxes method.
  • There is a scope violation. The updatedAmountOfFood variable is a local variable in another method.
  • The Party class is missing a constructor
  • There is a scope violation.

Activity 9.3.13.

Consider the following class definition.
public class Movie {
    private int currentPrice;
    private int movieRating;

    public Movie(int p, int r) {
        currentPrice = p;
        movieRating = r;
    }

    public int getCurrentPrice() {
        int currentPrice = 16;
        return currentPrice;
    }

    public void printPrice() {
        System.out.println(getCurrentPrice());
    }
}
Which of the following reasons explains why the printPrice method is β€œbroken” and only ever prints out a value of 16?
  • The private variables currentPrice and movieRating are not properly initialized.
  • The constructor will initialize them.
  • The private variables currentPrice and movieRating should have been declared public.
  • Instance variables should be private.
  • The printPrice method should have been declared as private.
  • Methods are usually public.
  • currentPrice is declared as a local variable in the getCurrentPrice method and set to 16, and will be used instead of the instance variable currentPrice.
  • Correct!
  • The currentPrice instance variable does not have a value.
  • Accessor methods are usually public.
You have attempted of activities on this page.