Thursday, 10 March 2016

Can we declare constructor as final?


This is the simple answer of the question.

If you ever try to declare a constructor as final then the fate of your program is fixed. The compiler will show the error - 'modifier final not allowed'

In Eclipse, try to write this :

public class check {
final check(){              // you will get compiler error at check()


You will get compiler error at check() with message :
'Illegal modifier for the constructor in type check; only public, protected & private are permitted'

Before we proceed further, take a note :
Constructor can never be inherited. (Learn why?)

Hope this will clear all the doubts!

Now why do we use final with any method or constructor?
Or why would you ever want a constructor to be final?

So that when a class is inherited then final constructor (or methods) of that class should not be overridden. But here we don't need to worry at all. Since constructor according to java rule book cannot be inherited so making it final doesn't make any sense.

You may also like to read:

No comments:

Post a Comment

If you are looking for a reference book on java then we recommend you to go for → Java The Complete Reference
Click on the image link below to get it now.