如何在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;
}
}
您可以用下面的简单方式编写:
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
}
}
假设Parent
嵌套在A
和Child
中的Parent
,Parent
和Child
都是嵌套的静态类,你可以这样做:
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");
}
}