Can a constructor be made final in Java?



A constructor is a special method in Java that is used to initialize objects. It gets called when an instance of a class is created. The constructor has the same name as the class and does not have a return type.

The question is whether a constructor can be declared or made final in Java?

The answer is no. Let's understand why.

Why can't we declare a Java Constructor "final"?

In Java, the final keyword is used to restrict modification of the members of a class (methods and variables). For example, a final method of a class cannot be overridden by its subclass.

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

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

Since constructors are not inherited in Java, you cannot override them. So, there is no need to declare a constructor final. Therefore, Java does not allow the final keyword before a constructor.

If we try, declare a constructor final, a compile-time error will be generated saying "modifier final not allowed here".

Example 1

In the following Java program, the Student class has a constructor that is final:

public class Student {
   public final Student(){
      System.out.println("This is a constructor");
   }
   public static void main(String args[]) {
      Student std = new Student();
   }
}

On compiling, the above program generates the following error:

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

Example 2

Following is an example of the constructor without the final keyword:

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

When you run the above code, you will see the following output:

This is a regular constructor

Conclusion

In conclusion, constructors in Java cannot be declared as final. The final keyword is not applicable to constructors because they are not inherited or overridden. Therefore, using final with a constructor will lead to a compilation error.

Remember, the primary purpose of a constructor is to initialize an object, and since it is not subject to inheritance or overriding, there is no need to restrict its modification using the final keyword.

Aishwarya Naglot
Aishwarya Naglot

Writing clean code… when the bugs aren’t looking.

Updated on: 2025-07-29T16:21:25+05:30

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements