The final modifier, for finalizing the implementations of classes, methods, and variables

The final modifier, for finalizing the implementations of classes, methods, and variables

Previous Home Next

 

Final Classes:

If a class is marked as final then no class can inherit any feature from the final class.

Final Variables:

A reference variable declared final can never be reassigned to refer to an different object.

Final Methods:
final modifier prevents a method from being modified in a subclass.


The main purpose of using a class being declared as final is to prevent the class from being sub- classed.

A final variable
can be explicitly initialized only once. 

The main intention of making a method final would be that the content of the method should not be changed by any outsider
 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
}
}






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

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

Previous Home Next