V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
n2l
V2EX  ›  问与答

关于 Java 中 protected 的使用疑问

  •  
  •   n2l · Apr 25, 2023 · 1383 views
    This topic created in 1109 days ago, the information mentioned may be changed or developed.

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

    7 replies    2023-04-26 08:55:55 +08:00
    JasonLaw
        1
    JasonLaw  
       Apr 25, 2023
    这种问题问 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  
       Apr 26, 2023 via iPhone
    自从有了 chatgpt 编程学起来也更简单了
    yungo8
        3
    yungo8  
       Apr 26, 2023 via Android
    很细节。第二张图实际是在不同包下面访问,所以访问不到。第三图是在 cat 的包下面访问,所以访问的到。你在第一个图里加个 main 一样可以用 animal 访问到 c
    n2l
        4
    n2l  
    OP
       Apr 26, 2023 via iPhone
    @yeqizhang 没懂,protected 是外包子类可以访问,那第二张图为啥看不见 c ?
    @fresco
    yungo8
        5
    yungo8  
       Apr 26, 2023 via Android
    @n2l 说的用子类可以,不是说子类里面用父类……相当于通过继承可以访问到父类细节
    darkengine
        6
    darkengine  
       Apr 26, 2023
    可以这么考虑,animal.c 是要访问 test.a1.Animal 的 c ,所以在 test.a2.Cat 里是访问不了的。new Cat().c 访问的是 Cat 类的成员 c (虽然它是从父类继承的)。
    n2l
        7
    n2l  
    OP
       Apr 26, 2023
    @yeqizhang 好的,谢谢。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1241 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 36ms · UTC 17:38 · PVG 01:38 · LAX 10:38 · JFK 13:38
    ♥ Do have faith in what you're doing.