Why can't a Java class be both abstract and final?


Abstract class

A class which contains 0 or more abstract methods is known as abstract class. If it contains at least one abstract method, it must be declared abstract.

If you want to use the concrete method in an abstract class you need to inherit the class, provide implementation to the abstract methods (if any) and then, you using the subclass object you can invoke the required methods.

Example

In the following Java example, the abstract class MyClass contains a concrete method with name display.

From another class (AbstractClassExample) we are inheriting the class MyClass and invoking the its concrete method display using the subclass object.

 Live Demo

abstract class MyClass {
   public void display() {
      System.out.println("This is a method of abstract class");
   }
}
public class AbstractClassExample extends MyClass {
   public static void main(String args[]) {
      new AbstractClassExample().display();
   }
}

Output

This is a method of abstract class

Final class

If you declare a class final you cannot extend if you try to extend a final class, a compile time error will be generated saying “cannot inherit from final SuperClass”

Example

In the following Java program, we have a final class with name SuperClass and we are trying to inherent it from another class (SubClass).

final class SuperClass {
   public void display() {
      System.out.println("This is a method of the superclass");
   }
}

Compile time error

On compiling, this program generates a compilation error as shown below −

SubClass.java:7: error: cannot inherit from final SuperClass
public class SubClass extends SuperClass{
                              ^
1 error

Both abstract and final

If you declare a class abstract, to use it, you must extend it and if you declare a class final you cannot extend it, since both contradict with each other you cannot declare a class both abstract and final if you do so a compile time error will be generated.

Example

public final abstract class Example {
   public void sample() {
   }
}

Compile time error

Example.java:1: error: illegal combination of modifiers: abstract and final

public final abstract class Example {
                      ^
1 error

Updated on: 14-Oct-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements