ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2019-11-11 12:13:49  阅读:387  来源: 互联网

标签:inner-classes 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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有