Can we declare constructor as final in java?


A constructor is used to initialize an object when it is created. It is syntactically similar to a method. The difference is that the constructors have the same name as their class and, have no return type.

There is no need to invoke constructors explicitly these are automatically invoked at the time of instantiation.

Example

 Live Demo

public class Example {
   public Example(){
      System.out.println("This is the constructor of the class example");
   }
   public static void main(String args[]) {
      Example obj = new Example();
   }
}

Output

This is the constructor of the class example

Final method

Whenever you make a method final, you cannot override it. i.e. you cannot provide implementation to the superclass’s final method from the subclass.

i.e. The purpose of making a method final is to prevent modification of a method from outside (child class).

Example

In the following Java program, we are trying to override a final method.

 Live Demo

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

Compile time error

On compiling, the above program generates the following error.

SubClass.java:10: error: display() in SubClass cannot override display() in SuperClass
final public void display() {
                  ^
overridden method is final
1 error

declaring constructor as final

In inheritance whenever you extend a class. The child class inherits all the members of the superclass except the constructors.

In other words, constructors cannot be inherited in Java, therefore, you cannot override constructors.

So, writing final before constructors make no sense. Therefore, java does not allow final keyword before a constructor.

If you try, make a constructor final a compile-time error will be generated saying “modifier final not allowed here”.

Example

In the following Java program, the Student class has a constructor which is final.

 Live Demo

public class Student {
   public final String name;
   public final int age;
   public final Student(){
      this.name = "Raju";
      this.age = 20;
   }
   public void display(){
      System.out.println("Name of the Student: "+this.name );
      System.out.println("Age of the Student: "+this.age );
   }
   public static void main(String args[]) {
      new Student().display();
   }
}

Compile time error

On compiling, the above program generates the following error.

Output

Student.java:6: error: modifier final not allowed here
public final Student(){
            ^
1 error

Updated on: 29-Jun-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements