Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Please look to the bolded section below for the answer needed: Scope and lifetim

ID: 3760813 • Letter: P

Question

Please look to the bolded section below for the answer needed:

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 in Java 7? Why does it compile in Java 8? What could it be modified so it would compile for Java 7?

Explanation / Answer

Firstly you can't declare a public static void main(String[] args) inside a nested class, unless you mark that class as static as well.Also the anonymous constructor you use to define the compare's compareTo method cannot access the non-final variable local. This is an error, because the variable might change during/after construction of the object. Hence, if you mark it as final, it is ensured that the variable cannot change in Java7.

For the above code to run on Java7 you either have to declare local as final:

Or define it as a static field of your class:

The modified code is as shown below which will work in Java7:

class AnonymousInnerClassInMethod
{
public static void main(String[] args)
{
   final int local = 1; //code changed here -- final added to variable local

Comparable compare = new Comparable ()
{
public int compareTo(Object value)
{
return (Integer)value - local;
}
};
System.out.println(compare.compareTo(5));
}
}