c# - Java和c#中 protected 成员的区别

标签 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
    }
}

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

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;
    }
}

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

with reference to this doc

最佳答案

不同之处在于,在 java 中,可以从同一个包访问 protected 成员。在 C++ 中,包级别的可见性在 Java 中没有等价物。

关于c# - Java和c#中 protected 成员的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22808357/

相关文章:

c# - 如何使用 Unity 映射泛型类型?

c# - 如何在 .NET 应用程序中隐藏加密 key ?

c# - 在 MVC5 应用程序中注册期间获取附加信息

java - 在 java 中反序列化 JSON 的最快方法是什么

java - 将 ArrayList<Integer> 变成一个数字?

c# - 多态/覆盖

c# - 如何将 bool 列表折叠成整数列表

java - Swing 相关组件和事件系统

C++ - 有没有办法只继承一些函数一次,而其他函数在多重继承中多次继承?

javascript - 所有面向对象的语言都会在内存中创建大量重复信息吗?