6. Scope and lifetime are distinct yet related issues in programming languages.
ID: 3553948 • Letter: 6
Question
6. 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? What could it be modified so it would compile? Explain the reason behind this failure in terms of scope and lifetime.
7. C++ allows pointers to stack-dynamic variables. Consider the following C++ function:
int twice(int x)
{
int *y;
*y = x * 2;
return *y;
}
Will the above function compile in C++? Is it correct? If not, under what circumstances will it fail and how should it be corrected? Consider one other language that has pointers. Does that language have the same problem? Explain.
Explanation / Answer
6.
The given code fragment does not execute because the scope of the variable local is limited to the outer class only. To compile and run this code, the keyword "final" must be added before the declaration of the vaiable "local".
Anonymous inner classes require final variables because of the way they are implemented in Java. An anonymous inner class (AIC) uses local variables by creating a private instance field which holds a copy of the value of the local variable. The inner class isn
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.