what is the use of keyword final?

2019-03-25 14:58发布

In the below code if i remove the keyword final from EditText i am an getting error in the line (6) where i pass EditText object (et) to the intent...I have to knw the significance of final keyword here...

final EditText et=(EditText)findViewById(R.id.t);
        Button b=(Button)findViewById(R.id.b1);
        b.setOnClickListener(new Button.OnClickListener(){
            public void onClick(View v)<br>
            {
            Intent on=new Intent(Intent.ACTION_CALL,Uri.parse("tel:"+et.getText()));
            startActivity(on);
            }
        });

7条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-03-25 15:49

It also helps to understand how Java creates an anonymous inner class. How Java implements that particular class.

Java needs for that variable to be final because the compiler must know the type of that object at compile time. The compiler will then generate a field within the anonymous inner class implementation (in this case 'et').

If the type is not final, how would the compiler determine how to build the inner class implementation. Basically, by declaring the field final, you are giving the Java compiler more information.

Code that doesn't help the compiler, won't compile your anonymous inner class:

Object et;
et = a ? new Object() : new EditText();

...

With the code above, the Java compiler cannot really build the anonymous inner class.

Your code:

final EditText et=(EditText)findViewById(R.id.t);

...

new Button.OnClickListener$1(){
            public void onClick(View v)<br>
            {
            Intent on=new Intent(Intent.ACTION_CALL,Uri.parse("tel:"+et.getText()));
            startActivity(on);
            }
        });

... The java compiler will create a bytecode class, an implementation of that inner class block that you provided that might look like this.

public class OnClickListener$1 {

 private final EditText et ; <---- this is important
 public OnClickListener$1(final et) {
    this.et = et;
 }
 public void onClick(View v)<br>
                {
                Intent on=new Intent(Intent.ACTION_CALL,Uri.parse("tel:"+et.getText()));
                startActivity(on);
                }
}

You can test the pseudo code I provided by finding the anonymous bytecode class $1 and decompile that bytecode file.

查看更多
登录 后发表回答