[英]How to access a private nested class object of a sole class that uses it in java
I have a base class in Java. 我在Java中有一个基类。 In that class I want to create a private class and I want to access the object of that private class in the base class. 在该类中,我想创建一个私有类,并希望在基类中访问该私有类的对象。 How can I do that? 我怎样才能做到这一点?
Thanks in advance! 提前致谢!
You can access an object of an inner class by creating it and remembering its reference. 您可以通过创建内部类并记住其引用来访问内部类的对象。 Just like an instance of any other class. 就像任何其他类的实例一样。
public enum Outer {;
private static class Nested {
private Nested() { }
}
public static Object getNested() {
return new Nested();
}
}
public class Main {
public static void main(String... args) {
System.out.println("I have an "+ Outer.newNested());
}
}
prints 版画
I have an Outer$Nested@3f0ef90c
A good example is from Arrays. 数组就是一个很好的例子。 This creates an instance of a private nested class which implements a public interface which makes it useful. 这将创建一个私有嵌套类的实例,该实例实现了一个使它有用的公共接口。
public static <T> List<T> asList(T... a) {
return new ArrayList<T>(a);
}
/**
* @serial include
*/
private static class ArrayList<E> extends AbstractList<E>
implements RandomAccess, java.io.Serializable
{
Do you mean this: 您的意思是:
class Test {
private Inner inner = new Inner();
private class Inner {
public void foo() {}
}
// later somewhere
public void bar() {
inner.foo();
}
}
PrivateClass c = new PrivateClass();
c.getSomeObject(); //??
You can use the above code in your base class; 您可以在基类中使用以上代码; provided the private class is an inner class of your base class. 前提是私有类是基类的内部类。
class Test {
private class Inner {
public void foo() {
System.out.println("vsahdashdashd");
}
}
// later somewhere
public void bar() {
new Inner().foo();
}
}
class javaapplication9 extends Test
{
public static void main(String[] args) {
Test inner = new Test();
inner.bar();
}
you can access private member from this type.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.