search

Home  >  Q&A  >  body text

java - 如何访问protected静态内部类?

如何访问一个受保护的静态内部类?

public class A{
    protected static class AInner{
        public void test(){
        }
    }
}
public class B extends A{
    public void hello(){
        //怎样才能访问AInner中的test方法呢?
    }
}

为什么当A和B在不同包中时,new AInner().test()会编译报错呢?
而当A和B在同一个包中,却不会报错?

高洛峰高洛峰2887 days ago319

reply all(2)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 17:50:11

    A B Different packages will report errors because the constructor of A.AInner is the default constructor, and the default access level allows children of the same package Class use's. A B不同包会报错是因为 A.AInner的构造器是默认构造器,而默认访问级别是允许同包的子类使用的。
    所以如果你可以改A类那么你可以写个 portected或者public级别的构造器。

    public AInner(){
    }
    

    如果你不改ASo if you can change class A then you can write a portected or public level constructor.

    package demo;
    
    public class A {
    
        protected static class Test {
            public void hello() {
                System.out.println("hello");
            }
        }
    
    }
    

    If you don’t change the A class, you can take a look at this.

    I wrote an accessible demo.
    STRUCTURE

    Category A:

    package test;
    
    import demo.A;
    
    public class B extends A {
        
         public static void main(String[] args) {
            // 这里B可以访问A的内部类,但不能访问内部类的构造器。
            // 所以这里实际B只能构造自己的内部类,所以下面用private修饰了这里依旧可以访问。
            // 所以这行代码实际是一种多态,父类类型变量指向子类引用。
            // 等同 A.Test t = new B.BTest();
             B.Test test = new B.BTest();
             test.hello();
         }
        
        // 因为那个内部类的class是protected的所以B类可以访问A.Test的class
        private static class BTest extends A.Test {
        
        }
    
    }
    
    #🎜🎜#Category B: #🎜🎜# rrreee

    reply
    0
  • 怪我咯

    怪我咯2017-04-17 17:50:11

    Why? protectedThe visibility range is determined by the visibility range, visible within packages and inherited classes.
    How to access? If you must force access, just modify the visibility through reflection.

    reply
    0
  • Cancelreply