Course Content‎ > ‎Session 5‎ > ‎

Final Variables and Methods

All methods and variables can be overridden by default in subclasses.  But if we wish to prevent the subclasses from overriding the members of the super class, we can declare them as final using the keyword final. For example,
 
final int size = 100;
final void showStatus()
{
...
}

Value of a final variable can never be changed. 
 
Final Variables
Final variables behave like class variables and they do not take any space on individual objects of the class. For example,  in the above Java code, size is a final variable, whose value remains constant and does not change.
 
Final Methods
When you declare a method as final, it ensures that the functionality defined in this method will never be altered in any way. In the above example, showStatus() method is declared as final, that is, it cannot be overridden. 

Comments