Scope and lifetime are distinct yet related issues in programming languages. Lan
ID: 3630809 • Letter: S
Question
Scope and lifetime are distinct yet related issues in programming languages. Languages can sometimes make design decisions that cause a conflict between the scope and the lifetime of variables. Java's decision to allow classes to be defined inside a method illustrates this conflict.Consider the following example:
class ClassInMethod
{
public static void main(String[] args)
{
int local;
class Inner
{
public void method()
{
local = 1;
}
}
}
}
Why does this code fail to compile? Explain the reason behind this failure in terms of scope and lifetime.
PLEASE EXPLAIN INDEPTHLY, thank you :)
Explanation / Answer
To access the variable "int local" within inner class you have to declare it as "final". like final int local ;