gpt4 book ai didi

java - Java 类 protected 成员的行为背后的逻辑

转载 作者:行者123 更新时间:2023-12-02 02:11:42 26 4
gpt4 key购买 nike

请有人向我解释一下这个特殊事实背后的逻辑(不是行为本身,而是逻辑),即仅允许通过继承(即通过子类型的引用)访问 protected 类成员(我认为包括方法和字段) – 而不是通过声明 protected 成员的父类型的引用 – 如果子类位于不同的包中?

如果父类和子类都在同一个包中,继承调用是否也是唯一允许的选项?

另外,为什么不允许从不同的继承树(C)访问另一个类(B)的 A protected 方法?

最佳答案

access to protected class members <...> is allowed through inheritance only i.e. by the reference of the child type – and not by the reference of the parent type where protected member was declared – in case child class is located in a different package ?

这是因为 protected 意味着从子类或同一包进行访问。从不同的类中,您只能访问同一包中的成员。这就是为什么您需要使用子类引用来引用成员。

what if both parent and child classes are in the same package, does call by inheritance is only allowed option as well?

如果调用者在同一个包中 - 您可以使用任何引用(父级或子级)

why it's not allowed to access A's protected methods for another class (B) from a different inheritance tree (C)?

代码很高兴看到,但从我对问题的理解来看,这正是 protected 修饰符需要做的。

关于java - Java 类 protected 成员的行为背后的逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49907803/

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