According to my knowledge, constructor never participate in inheritance, then under what circumstances we have to declare constructor as protected?
What do you mean by "never participate in inheritance"? While it is true that a constructor can't be overridden, but it can be called from the subclass. Hence, you need to define access to it -- be it from the subclass or any class that uses it.
When this can be used? I think in the case you *prefer* it to be subclassed, so abstract is too much. Think about a colleague who hates almost empty subclasses and does not want to extend your abstract Animal-class; you change it this way, explaining public was too much with good reasons, and go on with your work.
Probably you'll only use private and default and public. Java-engineers did not make the language on usage-statistics, but only left parts out which could lead to problems (such as multiple extension). So the question is the reverse: why wouldn't it be possible to make a class-instantiation protected?
if the constructor of a class is declared as protected, objects of that class cannot be created outside its package. And constructors will play a role in inheritance also. Only thing is that constructors are not inherited. A call to the super class constructor will be added in the constructor of the subclass by the compiler if the default constructor is there otherwise you will have to add the same.(ofcourse if there is a call to this(), call to super class constructor is not required.)
A call to the super class constructor will be added in the constructor of the subclass by the compiler if the default constructor is there otherwise you will have to add the same.(ofcourse if there is a call to this(), call to super class constructor is not required.)
The compiler will add a call to the default constructor of the superclass, when it finds a constructor. ie, it will add a super(), as the first line of the constructor.
when a call to this() is given, the compiler will go for the default constructor of the same class. since it can't contain a call to this() again(Recursive Contructor invocation error), the first line added will be super(). so it will perform the functionality implicitly.
Thanks<br /> <br />Anoobkumar<br />SCJP 1.5
Joined: Mar 29, 2007
Thanks a lot for each of you for spending your precious time for clearing my doubt.