开发者

Why does the scope work on classes created as parameters?

final TextView dob = (TextView) findViewById(R.id.TextView_DOB);
DatePickerDialog dateDialog = new DatePickerDialog(this,
        new DatePickerDialog.OnDateSetListener() {
                @Override
                public void onDateSet(DatePicker view, int year, int monthOfYear,
                        int dayOfMonth) {
                    Time dateOfBirth = new Time();
                    dateOfBirth.set(dayofMonth, monthOfYear, year);
                    long dtDob = dateOfBirth.toMillis(true);
                    dob.setText(DateFormat("MMMM dd yyyy", dtDob));
                    Editor editor = mGameSettings.edit();
                    editor.putLong(GAME_PREFERENCES_DOB, dtDob);
                    editor.commit();

                }
            },0,0,0);
return dateDialog;

Here, how can the class created on-the-fly inside the parameters of DatePickerDialog see "dob"? Surely it doesn't have the scope f开发者_StackOverflowor that?


It might help to look at the JLS in this case to understand how local classes are scoped.

http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.3

Here is the specific paragraph that answers your question --

The scope of a local class immediately enclosed by a block (§14.2) is the rest of the immediately enclosing block, including its own class declaration. The scope of a local class immediately enclosed by in a switch block statement group (§14.11)is the rest of the immediately enclosing switch block statement group, including its own class declaration.

EDIT --

Realized that that explanation specifically refers to the scope of the local class itself and not the scope of the enclosing members within the local class. Here is a better link --

http://docstore.mik.ua/orelly/java-ent/jnut/ch03_11.htm

Local classes have the following interesting features:

Like member classes, local classes are associated with a containing instance, and can access any members, including private members, of the containing class.

In addition to accessing fields defined by the containing class, local classes can access any local variables, method parameters, or exception parameters that are in the scope of the local method definition and declared final.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜