Home > Java > Inheritance > Final Keyword > Introduction
Introduction

Introduction to Final Keyword

Java’s final keyword has slightly different meanings depending on the context, but in general it says “This cannot be changed.” You might want to prevent changes for two reasons: design or efficiency.

 

Final Data Members


Final variables are often called constant variables (or just constants) because they do not change in value at any time.


With variables, the final modifier often is used with static to make the constant a class variable. If the value never changes, you don’t have much reason to give each object in the same class its own copy of the value. They all can use the class variable with the same functionality.


Syntax


class MyClass {

   //Final data member
    public static final int I = 60;


}


Final Methods


Final methods are those that can never be overridden by a subclass. You declare them using the final modifier in the class declaration.


The most common reason to declare a method final is to make the class run more efficiently. Normally, when a Java runtime environment such as the java interpreter runs a method, it checks the current class to find the method first, checks its superclass second, and onward up the class hierarchy until the method is found. This process sacrifices some speed in the name of flexibility and ease of development.


Syntax


class MyClass {

     //Final method
     public final void getSignature() {
        statement(s);
     }


}


Final Classes


When you say that an entire class is final (by preceding its definition with the final keyword), you state that you don’t want to inherit from this class or allow anyone else to do so. In other words, for some reason the design of your class is such that there is never a need to make any changes, or for safety or security reasons you don’t want subclassing. Alternatively, you might be dealing with an efficiency issue, and you want to make sure that any activity involved with objects of this class is as efficient as possible.


Note that the data members can be final or not, as you choose. The same rules apply to final for data members regardless of whether the class is defined as final. Defining the class as final simply prevents inheritance—nothing more. However, because it prevents inheritance all methods in a final class are implicitly final, since there’s no way to override them. So the compiler has the same efficiency options as it does if you explicitly declare a method final.


You can add the final specifier to a method in a final class, but it doesn’t add any meaning.


Syntax


final class MyClass {
}

Leave a Reply

Fields with * are mandatory.
* Name:
Website:
* Comments:
 
Tags allowed: <strong> <i> <u>
* Code:
 
 
Submit   Cancel