Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

why I need to define a parameter variable as final?

 
qionghua yang
Ranch Hand
Posts: 68
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi there,

I have this code for thread quick sort. If I don't define the variable first and pivot as final , I will have this error "local variable first is accessed from within inner class; needs to be declared as final". Can someone explain why? Thanks a lot!
public void threadQuickSort(final int first, int last)
{
final int pivot;
if (first < last)
{
pivot = partition(first, last);
(new Thread()
{
public void run()
{
quickSort(first, pivot);
}
}).start();
quickSort(pivot + 1, last);
}
}
qionghua
 
Sridevi Shrikanth
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Inner classes doesnot have access to method(local) variable.
The new instance of anonymous class is a inner class declared inside a method.
And tthese classes have access only to final variables declared in the method.
This is mainly because
U can create an instance of the inner class and return the refernce to any calling object. Inner classes always has an outer class reference associated with it. However it doesnot have the reference of the method variables. However Final is treated as a constant in Java.
For (eg)

if int 'i' is printed out, there will defintely be an error.
Hope this helps.
 
Priya Kannan
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Yang,
Doesn't this
(new Thread()
{
public void run()
{
quickSort(first, pivot);
}
}).start();
seem like an anonymous inner class implementing the Runnable interface defined inside a non static method? So the variables ought to be final if they are to be accessed within this method.
 
qionghua yang
Ranch Hand
Posts: 68
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks guys.
I guess I am not quite sure about anonymous inner class. Can you explain to me? Thanks!
qionghua
 
Steve Aldrich
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The thread can run even if ThreadQuickSort quits. When the method quits, all local variables no longer have meaning, their stack space is gone. The final variables and parameters of the method will still exist after the local variables have gone away, and will still be available, and valid, for use by the thread.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic