举个例子吧:
------------A---------------
package untitled3;
import java.io.*;public class A {
  protected String s="a";
}------------B----------------
package untitled3;
import java.io.*;
public class B
{
  public static void main(String[] args) 
  {
    A a = new A();
    System.out.println(a.s);
  }
}B不是A的子类,试问上面能直接输出a.s吗?

解决方案 »

  1.   

    From sun docs:
                class subclass package others
    private       X
    protected     X      X*       X
    Shouldn't Sun consider some kind of access modifier that make us able to open some part of our classes to subclasses but not to other classes in the same package (package and protected level)?
    Reply:
    Yes, that is how you would think protected would work. Java decided to change the meaning of protected to allow access to the package too.. I can only imagine that they expected all classes in one package to have the same author and so the enforcement could be skipped. If this was true though, they should have provided a way to make a package final so no new classes could be added to the package by outside developers. You could also include a warning in the Javadocs that the methods should only be used by sub-classes.  
     
      

  2.   

    理论上不应该可以这样调用。
    但java的字节码,在某些操作下能够调用到A的s。
      

  3.   

    我认为对.应该没有了. Sun把private protected取消掉了.
      

  4.   

    通过继承。protected关键字,只有在继承中的子类,才能访问该方法!将
    public class B  改为 public class B extends A
      

  5.   

    halfpro(学好Java):看来你还是没有学好JAVA,你把上面的例子跑一下再看。