How are java.lang.Object's protected methods protected from subclasses?

Posted by Adrian Lang on Stack Overflow See other posts from Stack Overflow or by Adrian Lang
Published on 2009-01-16T19:32:12Z Indexed on 2010/03/16 14:26 UTC
Read the original article Hit count: 316

Filed under:
|
|

The keyword protected grants access to classes in the same package and subclasses (http://java.sun.com/docs/books/tutorial/java/javaOO/accesscontrol.html).

Now, every class has java.lang.Object as superclass (http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html).

Hence I conclude that every class may access java.lang.Object's methods even if they are protected.

Take a look at the following example:

public class Testclass {
  public Object getOne() throws CloneNotSupportedException {
    return this.clone();
  }
  public Object getTwo() throws CloneNotSupportedException {
    return ((Object) this).clone();
  }
}

While getOne() compiles fine, getTwo() gives

Testclass.java:6: clone() has protected access in java.lang.Object
    	return ((Object) this).clone();

I neither understand why getTwo() doesn't compile nor what's the difference (regarding the access of java.lang.Objects members) with getOne().

© Stack Overflow or respective owner

Related posts about java

Related posts about protected