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

后端 未结 3 419
难免孤独
难免孤独 2020-12-28 10:18

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

3条回答
  •  梦毁少年i
    2020-12-28 10:49

    When you said "((Object) this).clone()", you accessed your own object via its superclass Object. You performed a widening conversion to an Object. The code then attempts to call clone on Object.

    But, as you've noted, clone is a protected method, meaning that only if your object was in the same package of java.lang would it be able to access the OBJECT's clone method.

    When you say this.clone, your class extended Object and thus had access to override or use clone directly through the protected class modifier because of inheritance. But that doesn't change the Object implementation.

    By saying ((Object) yourObject), you get something that is only accessible through the Object class. Only public methods of the Object class are accessible ouside of the package java.lang, so you get the compile-time exception, because the compiler knows this.

    By saying this.clone(), you are invoking your object's clone method that it got through inheriting through Object, and is now able to be invoked because it becomes a part of your custom subclass.

提交回复
热议问题