Java 静态嵌套类如何具有此指针

Java 静态嵌套类如何具有此指针,java,Java,今天我在读关于静态嵌套类的文章,由于下面的代码,我有点困惑 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; o

今天我在读关于静态嵌套类的文章,由于下面的代码,我有点困惑

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,这不是静态的,而且它怎么会有这个指针。因此,如果嵌套类是静态的,那么内部的方法是否隐式地是静态的?请澄清。

静态int x
而不是
int x
,这样它就可以工作了。正如您自己所说,静态内部类只能访问外部类的静态成员。由于
x
在代码中不是静态的,因此您无法访问它

附言

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

相反,非静态内部类是不同的。非静态内部类的每个实例都是一个闭包,即它与外部类的某个实例相关联。也就是说,如果不考虑外部类实例,就不能创建非静态内部类的实例

p.p.S


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

这与任何其他类的含义相同。它是指类的当前
实例
。可以实例化静态内部类(通常是):

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

编译示例:

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());
        }
    }
}
公共课{
私人名单学生;
公共课程(收集学生){
this.students=新数组列表(students);
Collections.sort(this.students,newstudentcomparator(-1));
}
私有静态类StudentComparator实现Comparator{
私人智力因素;
学生比较器(整数因子){
这个系数=系数;
}
@凌驾
公共整数比较(学生s1、学生s2){
返回this.factor*(s1.getName().compareTo(s2.getName());
}
}
}
但我感到困惑的是,如果它的行为类似于静态块,那么它允许我修改innerVar,这不是静态的

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

作者说,仔细阅读这个问题,他知道了这个错误的原因
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());
        }
    }
}
class testOuter {
   static int x;

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

   static void outerFunc(SINGLETON s) {
   }
}