Can you write a final constructor in Java?

When a class is inherited, the subclass inherits the methods and variables of super class but not constructors. For this reason, constructors are not members of class; only variables and methods are members of a class. As members are inherited, they are permitted by subclass to override with its own functionality.

When constructors are not inherited, no meaning of overriding the constructors. In Java, final is used by super class not to inherit its members by subclass. When constructor is not inherited (and subclass cannot override), then why a constructor should be declared final. Already, internally a constructor property is final. Why again, final is required. For this reason, constructor cannot be declared final. If final, compiler raises error.

Finally to say, a constructor cannot be final as it is never inherited.

Following code where constructor is declared final raises error.

public class Demo
{
  final Demo()   {    }		   // observe, final constructor; constructor can have any access specifier
}

Screenshot of compilation error of the above code.

ima

What other access modifiers a constructor cannot be?
"A constructor cannot be abstract, static, final, native, strictfp, or synchronized". Explained clearly in Java Constructor Properties

Some people think that there can be final constructor in a final class. Even it is wrong. The following code raises compilation error.

public final class Student	// observe, final class
{
   public final Student() {  }  // observe, final constructor
}

Screenshot of compilation error of the above code.

final constructor

3 thoughts on “Can you write a final constructor in Java?”

  1. Hello again sir!
    When we write constructor for a class after extending another class, we write super() keyword in order to access the parent constructor, so isn’t it inheriting the constructor?

    Thank you
    R. Vithu

Leave a Comment

Your email address will not be published.