0

For example, I try to do something in the separate thread:

public void shareQuote(final Context context, final ArrayList<Quote> quotes, final int number) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
        Toast warningWindow = Toast.makeText(context, context.getString(R.string.shareWarning), Toast.LENGTH_SHORT);
    } else {
        new Thread(new Runnable() {
            @Override
            public void run() {
                // Creates new intent for sharing
                Intent shareIntent = new Intent(Intent.ACTION_SEND);

                shareIntent.setType(SHARE_TYPE_TEXT);
                String subject = context.getString(R.string.quotes_author);
                String sharingQuote = "\"" + quotes.get(number).getText() + "\"" + "\n";
            }
        }).start();
    }

Why do I have to send the final objects to the arguments list if I want to do something in the new thread?

Adi Inbar
  • 12,097
  • 13
  • 56
  • 69
veinhorn
  • 2,363
  • 6
  • 21
  • 33

2 Answers2

3

Because anonymous classes only have access to final arguments (and final local variables), by design.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • The OP's example shows an anonymous class, rather than a local class, if I'm not mistaken. – jaco0646 Nov 10 '13 at 16:54
  • A class cannot be both local and anonymous. Though the two share many common features, there are also several important differences. Local classes are named, whereas anonymous classes are nameless. Local classes can be instantiated repeatedly, whereas anonymous classes can only be instantiated once, at the point of declaration. Due to their differences, the two are defined in different chapters of the JLS. Local classes are in chapter 14, as you noted. Anonymous classes are in [chapter 15](http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.9.5). – jaco0646 Nov 10 '13 at 17:35
  • Also see Tom Hawtin's explanation: http://stackoverflow.com/questions/478804/advantage-of-local-classes-java – jaco0646 Nov 10 '13 at 17:36
  • @jaco0646: Thanks, you're right, they don't use "local" with anonymous (even though that's what it is, the only significant difference is the name and implementing more than one interface). – T.J. Crowder Nov 10 '13 at 17:58
1

Java has strict scope rules. Your thread class is an anonymous class which means it will lose the outer scope after the method is finished. This means that anything that was in the methods stack frame will be removed.

When you add the key word final this prevents the field in your method from changing and allows that field to be added to the stack frame of inner class and the stack frame of your method. If the field wasn't final this couldn't be done as you could change where it points in your method and the inner class would not be aware of this change.

Chuck Lowery
  • 902
  • 6
  • 17