如何声明静态嵌套对象

问题描述 投票:0回答:2

如何在java中声明嵌套的静态对象并访问它们。

这是我目前的工作代码。我试图将孩子声明为静态,但这给了我一个错误。但在主要课堂上,我无法得到孩子。反正有没有实现这个目标?

public class A {

    public static Parent parent= new Parent("abc") {
            public Child child1 = new Child("efg1");
            public Child child2 = new Child("efg2");
    }


    public static Parent parent1= new Parent("abc") {
            public Child child3 = new Child("efg1");
            public Child child4 = new Child("efg2");
    }

}

public class Main{

    public void run() {
        A.parent.child1; //this is not working , the android studio can only access parent.
        A.parent1.child3;
    }
}
java oop
2个回答
1
投票

您可以用下面的简单方式编写:

public class Main {

    public void run() {
        Child child = A.parent.child1;
    }
}

class A {
    public static Parent parent = new Parent("abc");
}

class Parent {

    public Parent(String s) {
        // Do whatever with string s
    }

    public Child child1 = new Child("efg1");
    public Child child2 = new Child("efg2");
}

class Child {

    public Child(String s) {
        // Do whatever with string s
    }
}

0
投票

假设Parent嵌套在AChild中的ParentParentChild都是嵌套的静态类,你可以这样做:

public class A{
    public static class Parent {
       public Parent(String parentStr) {}

       public static class Child{
           public Child(String childStr) {}
       }
    }
}

public class Main{

    public void run() {
       A.Parent parent = new A.Parent("parent");
       A.Parent.Child child = new A.Parent.Child("child");
   }
}
© www.soinside.com 2019 - 2024. All rights reserved.