繁体   English   中英

如何从另一个 package 访问受保护的内部 class?

[英]How do I access a protected inner class from another package?

如何从 package“测试”中的“文件 2”访问 package“秘密”中“文件 1”中的内部 class“内部”。 这是它的代码:

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
    }
}

我知道关于这个主题有一个类似的问题( 如何在 package 之外访问受保护的内部 class? )但我似乎不明白答案。 这是我迄今为止尝试过的(从阅读答案):

第一次尝试:

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();
        }
    }
}

肯定似乎我错过了一些东西,引导我朝着正确的方向前进将会非常有用。

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

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();
    }
}

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

将可见性更改为公开。 无论如何,内部类主要用于与其父 class 中的私有字段进行交互。

您可以使用受保护的内部 class 的其他方式是,如果您要使用的 class 是子 class。 也就是说,内部 class 的父 class 正在被您要使用它的 class 继承。 在你的情况下


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


    package test;
    import secret.file1;
    
    public class file2 extends file1 {
        public static void main(String[] args) {
            File1 f = new File1();
            File1.Inner g = f.new Inner();
            System.out.println(g.x);
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM