举个例子吧:
------------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吗?
------------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吗?
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.
但java的字节码,在某些操作下能够调用到A的s。
public class B 改为 public class B extends A