In this Java article, you will learn how to use final keyword in Java with code example.

In Java, the final keyword can be applied to declaration of classes, methods and variables.

 

  • Java final class: if a class is marked as final, it cannot be subclassed/inherited by another class. For example:
            final class A { }
            
    then the following code will not compile:
            class B extends A {} // compile error
            
  • Java final method: when a method is final, that means it cannot be overriden, neither by methods in the same class or in sub class. For example:
            class C {
                final void foo() { }
            }
            
    the subclass D attempts to override the method foo(), but fail because foo() is marked as final:
            class D extends C {
                void foo() { } // compile error
            }
            
  • Java final variable: if a variable is marked as final, its reference cannot be changed to refer to another object, once initialized. For example:
            final String message = "HELLO";
            
    Once the variable message is initialized and marked as final, the following code attempts to assign another value to it, will fails:
            message = "BONJOUR";    // compile error
            

Note: a class cannot be both abstract and final.

 

See all keywords in Java.

 

Related Topics:

 

Other Recommended Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.



Add comment

   


Comments 

#3Gopalakrishnan2017-04-18 12:32
Sorry. I misunderstodd :(
Quoting Nam:
It is overload, not override.
Quoting Gopalakrishnan:
final class can be override by same class.

final void Test() {
}

public void Test(String str) {
}
Quote
#2Nam2017-04-18 06:21
It is overload, not override.
Quoting Gopalakrishnan:
final class can be override by same class.

final void Test() {
}

public void Test(String str) {
}
Quote
#1Gopalakrishnan2017-04-16 03:08
final class can be override by same class.

final void Test() {
}

public void Test(String str) {
}
Quote