impera Open Impera

AP Computer Science A · Class creation

Scope and the this keyword

1Scope of variables

The scope of a variable is the part of the program where it can be used.

  • Instance variables: the whole class (all methods and constructors).
  • Parameters: only inside their method or constructor.
  • Local variables: from their declaration to the end of the block { } they are declared in.
  • A loop variable declared in a for header exists only inside the loop.
for (int i = 0; i < 5; i++) {
    int sq = i * i;
}
System.out.println(i);    // compile error: i out of scope
Check yourself

Where can a local variable declared inside an if block be used?

  • Only inside that block, after its declaration

  • Anywhere in the method, once it has been declared

  • Anywhere in the class, in any of its methods

  • In other classes that create objects of this class

Show the answer

Only inside that block, after its declaration

Block scope.

2Shadowing

If a local variable or parameter has the same name as an instance variable, the local one shadows it: inside the method, the name refers to the local variable.

public class Pet {
    private String name;
    public Pet(String name) {
        name = name;     // assigns the parameter to itself!
    }
}

The instance variable stays null. This is a classic bug.

A parameter with the same name shadows the field; this.name reaches the field

Check yourself

In the Pet constructor above, what is the instance variable name after construction?

  • The parameter's value

  • A compile error occurs

  • null

  • ""

Show the answer

null

Parameter shadows the field.

3The this keyword

this is a reference to the current object: the object whose method or constructor is running.

Uses:

  • Distinguish instance variables from parameters: this.name = name;
  • Pass the current object to another method: other.addFriend(this);
  • Compare with another object: if (this == other).
public Pet(String name) {
    this.name = name;   // correct
}

this cannot be used in static methods, because there is no current object.

Check yourself

In this.name = name;, this.name refers to:

  • The parameter

  • A static variable

  • A local variable

  • The instance variable

Show the answer

The instance variable

Current object's field.

4Passing this

An object can pass itself to another object:

public class Student {
    private Course course;
    public void enrol(Course c) {
        course = c;
        c.addStudent(this);
    }
}

Now the course holds a reference to the very Student object that called enrol.

Check yourself

What does c.addStudent(this) pass?

  • A new copy of the current Student object

  • null, because this cannot be passed on

  • A reference to the current Student object

  • A reference to the Course object c itself

Show the answer

A reference to the current Student object

this is the current object.

5Going deeper: where a name is visible, shadowing bugs and passing this

Scope is the part of the program in which a name can be used.

Three kinds of variable

  • Instance variables: declared in the class, outside any method. Visible in every method and constructor of the class. They live as long as the object.
  • Parameters: visible only inside their method. Created at the call; gone at the return.
  • Local variables: visible from their declaration to the end of the block (the nearest enclosing braces). A variable declared in a for header exists only in that loop.
public int total(int[] values) {
    int sum = 0;
    for (int i = 0; i < values.length; i++) {
        int doubled = values[i] * 2;
        sum += doubled;
    }
    // i and doubled do not exist here
    return sum;
}

Using i or doubled after the loop does not compile.

Local variables must be initialized before use. Instance variables get defaults (0, 0.0, false, null); locals do not.

Declare a variable in the widest scope where it is needed. A value needed after the loop must be declared before the loop.

Worked example (find the error):

for (int k = 0; k < 5; k++) {
    int count = 0;
    count++;
}
System.out.println(count);
  1. count is declared inside the loop body.
  2. It is out of scope at the println: a compile error.
  3. Even moved inside, it would be reset to 0 on every pass. Declare it before the loop.

Shadowing: a local variable or parameter with the same name as an instance variable hides it within that method. The plain name then means the local one.

this is a reference to the current object: the object whose method or constructor is running. this.name always means the instance variable.

public class Student {
    private String name;
    private int grade;
    public Student(String name, int grade) {
        this.name = name;
        this.grade = grade;
    }
}

Without this, name = name; assigns the parameter to itself and the instance variable stays null.

Worked example (trace):

public class Box {
    private int size = 10;
    public void grow(int size) {
        size = size + 5;
    }
    public void expand(int amount) {
        size = size + amount;
    }
    public int getSize() {
        return size;
    }
}
// elsewhere:
Box b = new Box();
b.grow(3);
b.expand(3);
System.out.println(b.getSize());
  1. In grow, size is the parameter: it becomes 8 and is then discarded. The instance variable is still 10.
  2. In expand, there is no local size, so the instance variable becomes 13.
  3. Output: 13.

The accidental re-declaration: writing a type in front of an instance variable's name inside a method creates a new local:

public void reset() {
    int size = 0;       // a new local variable; the instance variable is untouched
}

Other uses of this

  • Calling one of the object's own methods: this.update(); is the same as update();.
  • Passing the current object to another method:
public void enroll(Course c) {
    c.addStudent(this);
}

The Course receives a reference to the very Student on which enroll was called.

  • Comparing with another object of the same class: return this.grade > other.grade;.

this does not exist in static methods, because no object is involved.

Access to another object's private data: code inside a class may use the private variables of any object of that class, not only this. In equals(Student other), other.name is legal.

Scope of methods: public methods can be called from other classes; private methods only from within the class.

Why narrow scope is good: a variable that exists only where it is needed cannot be changed by accident elsewhere, and names can be reused in different methods without conflict.

Common mistakes

  • Using a loop variable after the loop.
  • Declaring an accumulator inside the loop.
  • Forgetting this when a parameter shares an instance variable's name.
  • Re-declaring an instance variable as a local.
  • Using this in a static method.
  • Assuming a parameter's new value is seen by the caller.
Check yourself

Inside a constructor public Car(String model), which statement stores the parameter in the instance variable model?

  • model = model;

  • model = this.model;

  • this.model = model;

  • String model = model;

Show the answer

this.model = model;

this.model is the instance variable; plain model is the parameter.

6For top marks

  • Use different names for parameters and instance variables, or use this. consistently.
  • Declare accumulators in the right scope: a total needed after a loop must be declared before the loop.
  • Know that local variables have no default value: they must be assigned before use.
  • Remember that this is not available in static methods.
Example

a method that finds a maximum must declare int max = arr[0]; before the loop so it can be returned after the loop.

Check yourself

int total; for (...) { total += x; } fails to compile because:

  • Loops cannot change variables

  • total is out of scope

  • += is not allowed

  • total is not initialised before use

Show the answer

total is not initialised before use

Locals need a value.

Now test yourself

This lesson has a 8-question quiz and 5 exam-style questions with mark schemes in Impera. Free, with your progress saved.

Practise in Impera