Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Whats is the use of making a Constructor Protected

 
Haricharan Ramachandra
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

Can anyone please let me know what is the use of making a Constructor Protected. I know that if we make a Constructor private you can't instanciate that class. But if i make it Public or Protected i can still instanciate it. So what is the difference between maing a Constructor Protected instead of Public

thanks for your help in advance

thanks
Hari
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If a constructor is protected, then (outside of the package where it is defined) it can only be used by a subclass -- i.e., in a super() call.
 
sven studde
Ranch Hand
Posts: 148
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I know that if we make a Constructor private you can't instanciate that class.

Sure you can. A public method in a class can access private members--including private methods.

But if i make it Public or Protected i can still instanciate it. So what is the difference between maing a Constructor Protected instead of Public

A class that is not in the same package as a class that has a protected constructor cannot create objects of that class (that is assuming there is no helper method like in the above example). Or, in other words, if a class has a protected constructor, then only classes in the same package can create objects of that class.

On the other hand, if a class has a public constructor, then any class can create objects of that class.
[ October 27, 2006: Message edited by: sven studde ]
 
sven studde
Ranch Hand
Posts: 148
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a question that came to mind when thinking about the op's question: is there any effect in declaring a method protected if the method is not a constructor or a static method? It seems to me that if the method isn't a constructor or a static method, then it will only be called with an object of the class, and therefore protected has no meaning for such a method.

Ok, I just realized there are inheritance implications: a protected method will be inherited by a subclass unlike private methods, which aren't inherited. So, that means you can override the method in the subclass and therefore polymorphism will work.
[ October 27, 2006: Message edited by: sven studde ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic