编程语言
首页 > 编程语言> > java-为什么我不能通过内部类引用访问外部类数据成员?

java-为什么我不能通过内部类引用访问外部类数据成员?

作者:互联网

class OuterClass1 {

    static private int a = 10;

    void get() {
        System.out.println("Outer Clas Method");
    }

    static class StaticInnerClass {
        void get() {
            System.out.println("Inner Class Method:" + a);
        }
    }

    public static void main(String args[]) {

        OuterClass1.StaticInnerClass b = new OuterClass1.StaticInnerClass();
        b.get();
        System.out.println(b.a);
        System.out.println(b.c);

    }
}

我知道静态嵌套类可以访问外部类的数据成员,所以为什么我不能通过内部类引用访问外部类变量,但是可以通过直接在内部类中使用它来访问它(如上所述)?

解决方法:

Java语言规范提供了以下访问静态字段的规则:

◆ If the field is static:

  • The Primary expression is evaluated, and the result is discarded. […]
  • If the field is a non-blank final, then the result is the value of the specified class variable in the class or interface that is the type of the Primary expression.

注意,该规范不允许在其他类中搜索静态字段.仅考虑主表达式的直接类型.

在您的情况下,主要表达式就是b.对它进行了评估,其结果被丢弃,没有明显的效果.

主表达式b的类型为OuterClass1.StaticInnerClass.因此,Java将b.a视为OuterClass1.StaticInnerClass.a.由于OuterClass1.StaticInnerClass类不包含静态字段a,因此编译器会产生错误.

当您访问类的方法内部的字段时,一组不同的规则将生效.当编译器看到一个in

System.out.println("Inner Class Method:" + a);

它搜索类本身,并在不存在该字段时继续到外部类.那是编译器找到a的地方,因此表达式可以正确编译.

注意:通过非静态表达式访问静态成员是一个坏主意. See this Q&A for an explanation.

标签:inner-classes,java
来源: https://codeday.me/bug/20191111/2019787.html