gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:21:25 25 4
gpt4 key购买 nike

我在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com