0

今天我正在阅读有关静态嵌套类的内容,由于下面的代码,我有点困惑。

class testOuter {
    int x;
     static class inner {
       int innerVar; 
    public void testFunct() {
        x = 0;       // Error : cannot make static reference to non static field
        innerVar = 10;
        outerFunc(this);
     }
     }
     static void outerFunc(SINGLETON s) {
         
     }
}

我对静态嵌套类的理解是,它的行为就像外部类的静态成员。它只能引用静态变量,并且可以调用静态方法。从上面的代码来看,错误x=0是可以的。

但我感到困惑的是,如果它的行为类似于静态块,那么它允许我修改不是静态的 innerVar,以及它如何拥有这个指针。因此,如果嵌套类是静态的,那么内部的方法还是不是隐式静态的?

4

4 回答 4

1

static int x而不是int x,那么它将起作用。正如您自己所说,静态内部类只能访问外部类的静态成员。由于x在您的代码中不是静态的,因此您无法访问它。

附言

请注意,所有普通类都是静态的,即每次应用程序运行都存在一个类信息实例。因此,当您声明内部类为 时static,您只需声明它与普通类一样。

相反,非静态内部类是不同的。非静态内部类的每个实例都是一个闭包,即它与外部类的某个实例相关联。即你不能在不考虑外部类实例的情况下创建非静态内部类的实例。

聚苯乙烯

啊抱歉,您没有突出显示thisand innerVar。两者都是内部类的非静态成员,因此您可以访问它们。只有属于 OUTER 类的非静态成员才能访问。

于 2013-02-09T10:28:31.850 回答
1

this与任何其他类的含义相同。它指instance的是类的电流。静态内部类可以被实例化(通常是):

Inner inner = new Inner();

静态内部类的工作方式与任何其他类完全相同。唯一的区别是它可以通过将其设置为包含类的私有来使其对其他类不可见。

编译示例:

public class Course {
    private List<Student> students;

    public Course(Collection<Student> students) {
        this.students = new ArrayList<>(students);
        Collections.sort(this.students, new StudentComparator(-1));
    }

    private static class StudentComparator implements Comparator<Student> {
        private int factor;
        StudentComparator(int factor) {
            this.factor = factor;
        }

        @Override
        public int compare(Student s1, Student s2) {
            return this.factor * (s1.getName().compareTo(s2.getName());
        }
    }
}
于 2013-02-09T10:29:56.593 回答
0
class testOuter {
   static int x;

   static class inner {
     int innerVar; 
     public void testFunct() {
       x = 0;       
       innerVar = 10;
     }
   }

   static void outerFunc(SINGLETON s) {
   }
}
于 2013-02-09T10:34:23.537 回答
0

但我感到困惑的是,如果它的行为类似于静态块,那么它允许我修改不是静态的 innerVar

从静态内部类,您不能引用外部类的非静态成员innerVar属于您的静态内部类,因此在您访问它时没有错误。

于 2013-02-09T10:36:46.940 回答