Final class in Java

In java, class can also be final. But the restriction is that, final class can not be used to create subclass. It means, inheritance will not be possible for final class.

Example 1:


 final class A { //class
 public void hello(){
  System.out.println("Hello, World!");
 }
    
}
class Main {
    
public static void main(String[] args) {
 //invoke the method hello()
 new A().hello(); //run smoothly
 }
}

Output, you will get after running the above example:

Hello, World!

Though, A is final class but we can't use it for inheritance.

Thus, the following one will not work.


    final class A {
    public void hello(){
    System.out.println("Hello, World!");
    }
    
    }
    class HelloWorld extends A{
    
    public void hello(){
    System.out.println("Hello, Jenkov!");
    }
    public static void main(String[] args) {
    //invoke the method hello()
    new Main().hello();
    }
    }
   

If you now run the example above java class again, you will get the following error:

/**
* < error_message >
* Can not inherite final class A
*
*/

It's a very simple example post. Hope it make sense what we can and can't do with final class. But remember, sometimes it is really required to create final, for different use cases. When you basically don't allow other class to access your class members, then you can make your class as final. It applies super restrictions over class, class members.

Thanks for reading this article.