This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
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


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "protected member" Watch "protected member" New topic
Author

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
Sheriff

Joined: Oct 27, 2005
Posts: 19649
    
  18

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


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Pavan Kumar Dittakavi
Ranch Hand

Joined: Feb 12, 2011
Posts: 104

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

Thanks,
Pavan.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19649
    
  18

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: http://aspose.com/file-tools
 
subject: protected member
 
Similar Threads
private method overiding
Cannot create a concrete sub-class of a public abstract class, in another package
private and protected class?
Protected Constructor
static methods