Scope and lifetime are distinct yet related issues in programming languages. Lan
ID: 3549567 • 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 AnonymousInnerClassInMethod
{
public static void main(String[] args)
{
int local = 1;
Comparable compare = new Comparable ()
{
public int compareTo(Object value)
{
return (Integer)value - local;
}
};
System.out.println(compare.compareTo(5));
}
}
Why does this code fail to compile? Explain the reason behind this failure in terms of scope and lifetime.
Explanation / Answer
class AnonymousInnerClassInMethod
{
public static void main(String[] args)
{
int local = 1; // local variable to main()
Comparable compare = new Comparable ()
{ //anonymus inner class
public int compareTo(Object value)
{
return (Integer)value - local; //illegal usage
}
};
System.out.println(compare.compareTo(5));
}
}
=============================================
We are using a variable "local" inside an anonymus inner class which defined under main()
Compile error:
We Cannot refer to a non-final variable "local" inside an inner class defined in a different method::
This is why it doesn't work:
The variable "last" is local variables in the main() method. The object that you create with the anonymous class might last until after the main() method returns.
When the main() method returns, local variable (local) will be cleaned up from the stack, so it won't exist anymore after main() returns.
But the anonymous class object references this variable. Things would go horribly wrong if the anonymous class object tries to access the variables after they have been cleaned up.
Solution ::
By making last as "final", it is not really variable anymore, but constant. The compiler can then just replace the use of "last" in the anonymous class with the values of the constant (at compile time, ofcourse), and you won't have the problem with accessing non-existent variables anymore.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.