final keyword in java

The ” final ” keyword can be applied for variables,methods and classes.

final variable:

if a variable is marked as final, its reference can not be changed once initialized.

Example:

final int x=10;

Now variable “x” is called final variable and its value 10 can not be changed further and doing so will give compile time error.

the following code attempts to assign another value to it, will fail:

x=15;

final method:

If a method is marked as final, that means it can not be overridden in subclass.

Example:
  1. class Parent {
  2.  
  3.     final void display() {
  4.                             System.out.println("Hello");
  5.                          }
  6. }
  7.  
  8. class Child extends Parent {
  9.                                       void display() {System.out.println("Hi");
  10.                              // compile time error as final methods can't be overridden
  11.                            }
  12. }
class Parent {

    final void display() {
                            System.out.println("Hello");
                         }
}

class Child extends Parent {
                                      void display() {System.out.println("Hi"); 
                             // compile time error as final methods can't be overridden
                           }
}

final class:

If a class is marked as final, it can not be sub classed or it can not be inherited by another class.

Example:
  1. final class Parent {
  2. }
final class Parent {
}

then below code will not compile:

  1. class Child extends Parent {  
  2.             //  compile time error as final class can't be inherited
  3. }
class Child extends Parent {  
            //  compile time error as final class can't be inherited
}


Note:

A class can never be bothabstract and final.

abstract means the class must be extended,while final means it can not be, so it’s a kind of deadlock behavior if we make it as both abstract and final and hence Java does not allow such behavior.

A method can never be both abstract and final.

abstract means the method must be overridden, while final means it can not be, so its kind of deadlock behaviour if we make it as both abstract and final and hence Java does not allow such behavior.

" So Class and method can not be both abstract and final together but it can become abstract or final independently. "

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on