Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
The moose likes Java in General and the fly likes protected member Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "protected member" Watch "protected member" New topic

protected member

anish jain
Ranch Hand

Joined: Feb 03, 2010
Posts: 129
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

Joined: Oct 27, 2005
Posts: 20274

Sub classes can access their own version of the member but other classes can't.

How To Ask Questions How To Answer Questions
Pavan Kumar Dittakavi
Ranch Hand

Joined: Feb 12, 2011
Posts: 105

But since Object is the superclass of all classes, then why make a method like 'clone()' protected?

Rob Spoor

Joined: Oct 27, 2005
Posts: 20274

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.
I agree. Here's the link:
subject: protected member
It's not a secret anymore!