aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes why I need to define a parameter variable as final? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "why I need to define a parameter variable as final?" Watch "why I need to define a parameter variable as final?" New topic
Author

why I need to define a parameter variable as final?

qionghua yang
Ranch Hand

Joined: Oct 31, 2000
Posts: 68
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

Joined: Jan 11, 2001
Posts: 31
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

Joined: Jan 19, 2001
Posts: 72
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

Joined: Oct 31, 2000
Posts: 68
Thanks guys.
I guess I am not quite sure about anonymous inner class. Can you explain to me? Thanks!
qionghua
Steve Aldrich
Greenhorn

Joined: Jan 31, 2001
Posts: 7
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: why I need to define a parameter variable as final?