• Post Reply Bookmark Topic Watch Topic
  • New Topic

Protected members  RSS feed

 
Carlos Obregon
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Since I learned OOP I have never used protected members. I always thought they break encapsulation.

I read somewhere that while protected fields are bad, that sometimes protected methods make a lot of sense.

They use the clone() method as an example but I can't really understand what's the advantage of clone() beign protected rather than public.

Any thoughts?

Thanks a lot.
 
Edward Nelson
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[quote=Carlos Obregon]
what's the advantage of clone() beign protected rather than public.
[/quote]


clone() in the Object class is defined as protected in order to allow the implementation of cloning to be class-specific. It's something that any class might want to have, and will do so by calling Object::clone() and/or by extending the results. But it's also something that classes may not want to implement.

Also, classes that do implement cloning have the choice of making it public or not. If it was public already, there would be no such choice; it would necessarily be public in all classes.

Since some classes may not implement cloning, not all Objects can be cloned. This is why the designers of the Object class chose to make Object.clone() protected, to prevent its call on non-cloneable objects.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!