Can a constructor be made final in Java?

Java 8Object Oriented ProgrammingProgramming

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)
raja
Published on 08-Jan-2018 11:10:49
Advertisements