1 April 2022

The Dope on Scope

State and Static Data These are visible anywhere inside of the class. Static data that are public are visible and can be called via the class's name.

Methods These are visible outside of the class only if they are marked public.

If a method is public and static, you may call it via the class name outside of the class.

If the method is an instanance method and it is public, you may call it via an instance of the class.

Local Variables These are visible only inside of the method they are defined in. This rule includes all parameters passed to the method.

We define a variable's block as being the code inside of the closest set of enclosing curly braces. A variable is visible only inside of its block. A varible is never visible before it is declared.

Because of this, we say that Java has block scope. This is a tighter rule than Python's function scope.

Observe this.


/**************************************************
*   Author: Morrison
*   Date:  01 Apr 202022
**************************************************/

public class BlockHead 
{

    public static final int IQ;
    static
    {
        IQ = 6;   //Outside this is BlockHead.IQ
    }
    private int quack;  //visible inside class but not out
    public BlockHead(int quack)
    {
        this.quack = quack;  
    }
    public int foo(int x)   //this x is private to foo
    {
        return x*quack;     //quack is visible here
    }
    
    public static void main(String[] args)
    {
        int x = 15;   //this variable is visible anywhere
        if(x > 10)    //in main.
        {
            int y = 4;    //this variable dies at the
        }                 //end of this block
        else
        {
            y = 2;
        }
    }
}

Compile and get a scolding.

javac BlockHead.java 
BlockHead.java:33: error: cannot find symbol
            y = 2;
            ^
  symbol:   variable y
  location: class BlockHead
1 error

Here is how to get this to compile.


/**************************************************
*   Author: Morrison
*   Date:  01 Apr 202022
**************************************************/

public class BlockHead 
{

    public static final int IQ;
    static
    {
        IQ = 6;   //Outside this is BlockHead.IQ
    }
    private int quack;  //visible inside class but not out
    public BlockHead(int quack)
    {
        this.quack = quack;
    }
    public int foo(int x)   //this x is private to foo
    {
        return x*quack;
    }
    
    public static void main(String[] args)
    {
        int x = 15;   //this variable is visible anywhere
        int y = 0;    //initalize here
        if(x > 10)    //in main.
        {
            y = 4;    //now simply assign here
        }                 
        else
        {
            y = 2;
        }
    }
}

BigInteger