Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the use of keyword final?

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);
            }
        });
like image 428
satheesh.droid Avatar asked Dec 29 '10 18:12

satheesh.droid


People also ask

What are the 3 uses of final keyword in Java?

Final keyword in Java has three different uses: create constants, prevent inheritance and prevent methods from being overridden.

What is the use of final keyword in C++?

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.

What is the use of final class in Java?

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.

What is final keyword in oops?

The final keyword is used to prevent a class from being inherited and to prevent inherited method from being overridden.


2 Answers

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.

like image 183
Vladimir Ivanov Avatar answered Oct 10 '22 02:10

Vladimir Ivanov


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.

like image 23
Will Avatar answered Oct 10 '22 02:10

Will