Quick Index
Examples


For the class you are coding in (e.g. "Rectangle" here) you have scope to all the other methods in the same class.

  • Declared method "computeArea"
  • We have scope to it so we call "computeArea"
  • We'll also discuss method scope relative to inheritance in upcoming chapters
public class Rectangle {
	private int width;
	private int height;

	public int 
1
computeArea()
{ return width * height; } public String toString() { int a =
2
computeArea(); return "Rectangle: area = " + a; } }

  • We call method "cube" on "this" (meaning this object)
  • We call method "square" on "this"
But we get a compile error like this:
cannot find symbol
symbol: method cube()


We do not have methods "cube" or "square" in our scope (vision). We cannot see them.
public class BrilliantNumber {

	private int number;

	public BrilliantNumber(int newNumber) {
		this.number = newNumber;
	}

	public double cubeOverSqure() {
		double y = 
1
this.cube() /
2
this.square(); return y; } }
  • We add the method "square"
  • We add the method "cube"
  • We call method "cube" on "this"
  • We call method "square" on "this"
The compile error is now gone because we yes do have scope (vision) to "cube" and "square'. We can see them. They are in our context and scope.
public class BrilliantNumber {

	private int number;

	public BrilliantNumber(int newNumber) {
		this.number = newNumber;
	}

	
1
public int square()
{ int num, result; num = this.number; result = num * num; return result; }
2
public int cube()
{ int num, result; num = this.number; result = num * num * num; return result; } public double cubeOverSqure() { double y =
3
this.cube() /
4
this.square(); return y; } }

Scope When Sending Messages to Other Objects


Here we look at scope when sending messages to other objects.

Here we send two messages to another object.

We can do this as long as those methods specify public access.
public class RectangleTest {

	public void test1() {
		Rectangle rec = new Rectangle(10, 5);
		int w, h;
		w = rec.getWidth();
		h = rec.getHeight();
	}

}