• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

protected member

 
anish jain
Ranch Hand
Posts: 129
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is the use of making a method protected?

For eg. clone() method of Object class is protected. What is achieved by making it protected?
 
Rob Spoor
Sheriff
Pie
Posts: 20661
65
Chrome Eclipse IDE Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sub classes can access their own version of the member but other classes can't.
 
Pavan Kumar Dittakavi
Ranch Hand
Posts: 106
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But since Object is the superclass of all classes, then why make a method like 'clone()' protected?

Thanks,
Pavan.
 
Rob Spoor
Sheriff
Pie
Posts: 20661
65
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because Sun didn't want to make it public; that would mean that every single class would have a clone() method, even those that don't need one. Because it's protected, classes that want to have it can make it public (increase visibility), and call super.clone() to do the hard work. For instance, from java.util.Locale:
Here super.clone() is used to create a basic clone - an object of the exact same class with all fields copied directly. This is better than using "new Locale(...)" because sub classes couldn't call super.clone() anymore and get an object of that sub class.

Two more examples, from java.util.AbstractMap and java.util.HashMap (with HashMap extending AbstractMap):
AbstractMap calls super.clone() and then changes two references that were copied into null; after all, these two variables should not have shared values between two instances. HashMap calls super.clone() which returns a HashMap, because AbstractMap also used super.clone(). The rest of the method is making sure the original and the clone do not share objects but will contain the same key-value pairs.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic