V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
n2l
V2EX  ›  问与答

关于 Java 中 protected 的使用疑问

  •  
  •   n2l · 359 天前 · 887 次点击
    这是一个创建于 359 天前的主题,其中的信息可能已经有所发展或是发生改变。

    为什么 animal 看不见 c ? Snipaste_2023-04-25_22-03-02.jpg

    7 条回复    2023-04-26 08:55:55 +08:00
    JasonLaw
        1
    JasonLaw  
       359 天前
    这种问题问 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
        2
    fresco  
       359 天前 via iPhone
    自从有了 chatgpt 编程学起来也更简单了
    yeqizhang
        3
    yeqizhang  
       359 天前 via Android
    很细节。第二张图实际是在不同包下面访问,所以访问不到。第三图是在 cat 的包下面访问,所以访问的到。你在第一个图里加个 main 一样可以用 animal 访问到 c
    n2l
        4
    n2l  
    OP
       359 天前 via iPhone
    @yeqizhang 没懂,protected 是外包子类可以访问,那第二张图为啥看不见 c ?
    @fresco
    yeqizhang
        5
    yeqizhang  
       359 天前 via Android
    @n2l 说的用子类可以,不是说子类里面用父类……相当于通过继承可以访问到父类细节
    darkengine
        6
    darkengine  
       359 天前
    可以这么考虑,animal.c 是要访问 test.a1.Animal 的 c ,所以在 test.a2.Cat 里是访问不了的。new Cat().c 访问的是 Cat 类的成员 c (虽然它是从父类继承的)。
    n2l
        7
    n2l  
    OP
       358 天前
    @yeqizhang 好的,谢谢。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3383 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 00:40 · PVG 08:40 · LAX 17:40 · JFK 20:40
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.