The final Modifier

The final Modifier

Previous Home Next

 

The final modifier indicates that a data field cannot be modified.
Final modifier is used on the class,method,field and variable.

When Final modifier used on class
the class cannot be sub classed

When the final modifier used on method
 the method cannot be overridden

When the final keyword used on field
the field cannot change its value. static final fields are compile-time constants.

When the final modifier used on variable
 the variable cannot changed its value
 


 Final class declaration:
public final class Demo
{
// body of class
}


Final variable declaration


class Demo
{
final int value= 25;
// examples of declaring constants:
public static final int BOXWIDTH = 6;
static final String TITLE = "Executive";

public void changeValue()
{
value = 30; //will give an error

}

The above program will give an error because final variable cannot be changed


The Final Method Declaration


class Demo
{
public final void changeSalary(){
// body of method
}
}





Previous Home Next