No enclosing instance of type Outer is accessible. Must qualify the allocation with an enclosing instance of type Outer (e.g. x.new A() where x is an instance of Outer)
2016-03-04 22:55
776 查看
之前看内部类的时候没发现这个问题,今天写代码的时候遇到,写个最简单的例子:
下面这一段代码
红色的部分就是编译报错:
根据提示,没有可以访问的实例Outer,必须分配一个合适的外部类实例以访问内部类。
正确的方式可以是:
或者:
关于内部类
依然是一个独立的类,在编译之后会内部类会被编译成独立的.class文件,但是前面冠以外部类的类命和$符号。
内部类不能用普通的方式访问。内部类是外部类的一个成员,因此内部类可以自由地访问外部类的成员变量,无论是否是private的。
成员内部类内不允许有任何静态声明!
能够访问成员内部类的唯一途径就是通过外部类的对象!
有关内部类具体可参考
http://blog.csdn.net/ft305977550/article/details/8350708
仅仅记录编程中遇到的问题。
下面这一段代码
红色的部分就是编译报错:
No enclosing instance of type Outer is accessible. Must qualify the allocation with an enclosing instance of type Outer (e.g. x.new A() where x is an instance of Outer).
根据提示,没有可以访问的实例Outer,必须分配一个合适的外部类实例以访问内部类。
正确的方式可以是:
public class Outer { private int i = 10; class Inner{ public void seeOuter(){ System.out.println(i); } } public static void main(String[] args) { Outer out = new Outer(); Inner in = out.new Inner(); in.seeOuter(); } }
或者:
public class Outer { private int i = 10; static class Inner{ public void seeOuter(){ // 静态内部类不能直接访问外部类的非静态成员,但可以通过 new 外部类().成员 的方式访问 //System.out.println(i);这句话编译不过 System.out.println(new Outer().i); } } public static void main(String[] args) { Inner in = new Inner(); in.seeOuter(); } }
关于内部类
依然是一个独立的类,在编译之后会内部类会被编译成独立的.class文件,但是前面冠以外部类的类命和$符号。
内部类不能用普通的方式访问。内部类是外部类的一个成员,因此内部类可以自由地访问外部类的成员变量,无论是否是private的。
成员内部类内不允许有任何静态声明!
能够访问成员内部类的唯一途径就是通过外部类的对象!
有关内部类具体可参考
http://blog.csdn.net/ft305977550/article/details/8350708
仅仅记录编程中遇到的问题。
相关文章推荐
- 第二次作业
- gdb ps
- bzoj 1293: [SCOI2009]生日礼物
- blog上QQ权限-我的第一篇markdown练习
- DSP 2812: 使用C++实现的SCI主动站程序框架
- [POJ] 1201 Intervals [差分约束]
- P/NP/NPC/NP-hard概念的图形解释
- Hbase 批量数据BulkLoad 导入使用
- Hust oj 1184 早起一水(简单贪心)
- 解决Gradle DSL method not found: ‘android()’
- day16
- JAVA类课后练习
- C/C++中的回车与换行
- hadoop介绍
- App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Te
- Inorder Tree Traversal without recursion and without stack!
- apache2.4配置php5.6.19出现“Cannot load F:/php5.6.19/php5apache2_4.dll into server”错误
- 寒假刷题-动态规划
- moon 英文单词 2016.03.04
- bzoj 1263: [SCOI2006]整数划分