What is final keyword in java?

final keyword in java

final is one of the java keyword which can be applied to variables, method, and classe and the meaning is once final is applied, it's value or state can not be chnaged

what is final keywords for variables:-

if we apply final keyword to fields or meber variables , the varibles are tread as constants, that means once created , and assigned the value, The value can not be changed
final int value=20;
// Gives compile time error for the below line of code
value=40;

So you have to use the fields as final whenever the value of the field can not be changed once it is initialized.

what is final keywords for methods

:-
methods also can be declared as final. A final method can not be overriden in a sub class

following is the usage of final method
class SuperClass {
 public final void method1() {

 }

 public int method2() {
  return 0;

 }
}

class SubClass extends SuperClass {
 // the following method throws Compile time exception as this method has
 // been declared in Superclass.Final methods ca
 public final void method1() {

 }

 // This works fine
 public int method2() {
  return 0;

 }
 

what is final keywords for classe

:-

if we mark the class as final, the class can not be extended by other class. This makes the class as some specific class which is secure.
Most of the classes in java.lang.Math classes are final classes.
The compiler will throws error if we extends the final class.

Here is the example for final class
public final class SuperClass {

}

// the following class throws Compile time exception as the Superclass declared
// as final

class SubClass extends SuperClass {

}


Final as argument to the method

:-

You can also pass the final keyword to the parameters to the methods. That means the parameters can not be changed and local to the method

public void getValue(final int i){
  
 }


Please click on +1 button if you like this post

No comments:

Post a Comment

Note: only a member of this blog may post a comment.