Can a constructor be made final in Java?


No, a constructor can’t be made final.

A final method cannot be overridden by any subclasses. As mentioned previously, the final modifier prevents a method from being modified in a subclass.

The main intention of making a method final would be that the content of the method should not be changed by any outsider.

But, in inheritance sub class inherits the members of a super class except constructors.

In other words, constructors cannot be inherited in Java therefore, there is no need to write final before constructors. Therefore, java does not allow final keyword before a constructor. If you try a compile time error is generated as in the following example.

Example

public class Sample {
   public static void main(String args[]){
      int num;
      final public Sample(){
         num = 30;
      }
   }
}

Output

Exception in thread "main" java.lang.Error: Unresolved compilation problems:
   Syntax error, insert "enum Identifier" to complete EnumHeaderName
   Syntax error, insert "EnumBody" to complete BlockStatement
   Syntax error, insert ";" to complete Statement
   at newJavaExamples.Sample.main(Sample.java:6)

Updated on: 30-Jul-2019

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements