No, we cannot declare a constructor final
in Java. If we try making a constructor final there will be a compile time error. Now, let's understand why can't we make constructor 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 its class and have no return type.
In inheritance whenever we extend a class, subclass inherits all the members of the superclass except the constructors. In other words, constructors cannot be inherited in Java, hence, we cannot override them. Therefore, java does not allow final
keyword before a constructor. Let's try to compile following piece of code and see what it says?
public class Test { final Test() { } }
If we try making a constructor final
a compile-time error will be generated saying Illegal modifier for the constructor in type Test; only public, protected and private are permitted.
Hope we have enjoyed reading this post. Please do write us if we have any suggestion/comment or come across any error on this page. Thank we for reading!
Share this page on WhatsApp