开发者

How come protected method is accessible in unrelated class?

I have below code written with Eclipse ide:

public interface X
{
  final public static int SOME_CONST = 0;
}
public class Handle implements X
{
  protected void methodHandle () { }
 //...
}

public class User implements X
{
  Handle handle = new Handle();
  private void methodUser ()
  {
    Y y = new Y()  // anonymous inner class
    {
      public void methodY ()
      {
        handle.methodHandle (); // <--- why this is NOT giving error ?
      }
    }
  }
}

Even though Handle.me开发者_JS百科thodHandle () is protected, it's still callable from the inner method of an anonymous inner class method ? Why is it happening, am I missing something ? The only relation between Handle and User is that they are implementing same X.


If both classes are in the same package, the protected method can be called.

See this for more details.


If the calling class is in the same package, it is going to be able to call protected methods. If that's not what you wanted, you should make your methods private.


Classes in the same package are not 'unrelated'.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜