Friday, December 30, 2011

What is final keyword in java?

final keyword in java

java final keyword
final is one of the Java keywords which can be applied to variables, method, and class and the meaning is once final is applied, it's value or state cannot be changed

what is final keywords for variables:-

if we apply the final keyword to fields or member variables, the variables 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 cannot be changed once it is initialized.

what are final keywords for methods

also can be declared as final. A final method cannot be overridden in a subclass

following is the usage of a 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 are final keywords in a class

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 an error if we extends the final class.

Here is the example for the 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 an 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


EmoticonEmoticon

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