关于 Java 中 protected 的使用疑问

2023-04-25 22:04:30 +08:00
 n2l

为什么 animal 看不见 c ?

894 次点击
所在节点    问与答
7 条回复
JasonLaw
2023-04-25 22:33:05 +08:00
这种问题问 ChatGPT 最好了。

In Java, the protected keyword is a visibility modifier that can be applied to class members (fields, methods, and nested classes) to restrict their access to the class itself, its subclasses, and other classes in the same package.

More specifically, when a class member is declared as protected, it can be accessed by:

The class itself
Any subclass of the class, even if the subclass is in a different package
Any other class in the same package as the class
fresco
2023-04-26 00:08:20 +08:00
自从有了 chatgpt 编程学起来也更简单了
yeqizhang
2023-04-26 00:37:37 +08:00
很细节。第二张图实际是在不同包下面访问,所以访问不到。第三图是在 cat 的包下面访问,所以访问的到。你在第一个图里加个 main 一样可以用 animal 访问到 c
n2l
2023-04-26 06:56:33 +08:00
@yeqizhang 没懂,protected 是外包子类可以访问,那第二张图为啥看不见 c ?
@fresco
yeqizhang
2023-04-26 07:43:40 +08:00
@n2l 说的用子类可以,不是说子类里面用父类……相当于通过继承可以访问到父类细节
darkengine
2023-04-26 08:34:43 +08:00
可以这么考虑,animal.c 是要访问 test.a1.Animal 的 c ,所以在 test.a2.Cat 里是访问不了的。new Cat().c 访问的是 Cat 类的成员 c (虽然它是从父类继承的)。
n2l
2023-04-26 08:55:55 +08:00
@yeqizhang 好的,谢谢。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/935482

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX