【问题标题】:How do I access a protected inner class from another package?如何从另一个包访问受保护的内部类?
【发布时间】:2021-03-13 20:26:32
【问题描述】:

如何从包“test”中的“file2”访问包“secret”中“file1”中的内部类“Inner”。这是它的代码:

package secret;

public class file1 {
    protected class Inner {
        public int x = 8;
    }
}
package test;
import secret.file1;

public class file2 {
    public static void main(String[] args) {
        // code
    }
}

我知道关于这个主题有一个类似的问题 (How to access protected inner class outside package?),但我似乎不明白答案。这是我迄今为止尝试过的(通过阅读答案):

第一次尝试:

public class file2 extends file1 {
    public static void main(String[] args) {
        file1 outer = new file1();
        file1.Inner inner = outer.new Inner();
    }
}

第二次尝试:

public class file2 extends file1 {
    public static class file3 extends file1.Inner {
        public static void main(String[] args) {
            file1 outer = new file1();
            file1.Inner inner = outer.new Inner();
        }
    }
}

尝试 3:

public class file2 extends file1 {
    public static class file3 extends file1.Inner {
        public static void main(String[] args) {
            file2 outer = new file2();
            file2.file3 outerinner = outer.new file3();
            file2.file3.Inner inner = outerinner.new Inner();
        }
    }
}

似乎我确实错过了一些东西,引导我朝着正确的方向前进会非常重要。

【问题讨论】:

  • 使用反射。然而,真正的问题是,你为什么需要这样做?

标签: java class object oop inner-classes


【解决方案1】:

有一个使用第三类的解决方法:

package secret;

public class file3 extends file1 {
    public Inner createInner(){
        return new Inner();
    }
}

然后简单地说:

public class file2 extends file1 {
    public static void main(String[] args) {
        file3 outer = new file3();
        file1.Inner inner = outer.createInner();
    }
}

【讨论】:

    【解决方案2】:

    检查您的类层次结构设计是否无法简化。将重点放在内部嵌套类和静态嵌套类之间的区别上。 或者想出类似这样的文件 file1 x = new inner();

    【讨论】:

      猜你喜欢
      • 2013-07-10
      • 2015-11-05
      • 2014-06-24
      • 2016-05-26
      • 2012-05-09
      • 2020-11-02
      • 1970-01-01
      • 1970-01-01
      • 2012-07-22
      相关资源
      最近更新 更多