Java和c#中受保护的成员差异

6 c# java oop protected

我在Java中有以下代码

public class First {
    protected int z;

    First()
    {
        System.out.append("First const");
    }

}

class Second extends First {

    private int b;
    protected int a;

}

class Test {
    /**
     * @param args the command line arguments
     */
    int a=0;

    public static void main(String[] args) {
        // TODO code application logic here
        First t=new Second();
        t.z=10; work fine
        First x=new First();
        x.z=1; // works fine
    }
}
Run Code Online (Sandbox Code Playgroud)

所以我可以z通过创建base类的对象来访问

C#

class A
{
    protected int x = 123;
}

class B : A
{
    static void Main()
    {
        A a = new A();
        B b = new B();

        // Error CS1540, because x can only be accessed by 
        // classes derived from A. 
        // a.x = 10;  

        // OK, because this class derives from A.
        b.x = 10;
    }
}
Run Code Online (Sandbox Code Playgroud)

所以我无法访问a,如果通过基类对象.从一个OOP角度来看,我发现Java和C#相似,两种语言对于protected成员有什么区别吗?

参考这个文件

tib*_*tof 4

不同之处在于,在java中,可以从同一个包访问受保护的成员。在 C++ 中,Java 中的包级别可见性没有等效项。