Why is it declared final when using local variables in an anonymous class?

Source: Internet
Author: User

When there are two threads inside a method that share internal class objects, the local variables of this method can be accessed,

It becomes a critical resource, causing the program to be unstable, so it must be final.

Anyway, Java is not allowing you to change the local variables of the method inside the local inner class.

public class MyBase {

Public anoclass func (final int i) { 
return new Anoclass () { 
int j=i; 

System.out.println ("Anonymous Inner class"); 

public void Func () { 
System.out.println ("Inner anoclass"); 

}; 

/** 
* @param args 
*/ 
public static void Main (string[] args) { 
MyBase MyBase = new MyBase (); 
Anoclass Anoclass = Mybase.func (5); 
Anoclass.func (); 
}

}

Class anoclass{
public void Func () {
System.out.println ("Anoclass.");  

}

Why is it declared final when using local variables in an anonymous class?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.