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);
}
});
Final keyword in Java has three different uses: create constants, prevent inheritance and prevent methods from being overridden.
You can use the final keyword to designate virtual functions that cannot be overridden in a derived class. You can also use it to designate classes that cannot be inherited.
The main purpose of using a class being declared as final is to prevent the class from being subclassed. If a class is marked as final then no class can inherit any feature from the final class. You cannot extend a final class. If you try it gives you a compile time error.
The final keyword is used to prevent a class from being inherited and to prevent inherited method from being overridden.
It is because you use closure here. It means that inner class uses the context of the inbounded one. To use it the variables should be declared final in order not to be changed.
See more here.
Final essentially means that the variable et
will not be reassigned at any point and will remain around. This means that inner classes, like your listener, can trust that it wont be reassigned by some other thread which could cause all kinds of trouble.
final can also be used to modify a method or class definition, that would mean that the method can't be overriden by a subclass, or that the class cannot be extended.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With