[英]How to access a private nested class object of a sole class that uses it in java
我在Java中有一個基類。 在該類中,我想創建一個私有類,並希望在基類中訪問該私有類的對象。 我怎樣才能做到這一點?
提前致謝!
您可以通過創建內部類並記住其引用來訪問內部類的對象。 就像任何其他類的實例一樣。
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());
}
}
版畫
I have an Outer$Nested@3f0ef90c
數組就是一個很好的例子。 這將創建一個私有嵌套類的實例,該實例實現了一個使它有用的公共接口。
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
{
您的意思是:
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(); //??
您可以在基類中使用以上代碼; 前提是私有類是基類的內部類。
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.