zoukankan      html  css  js  c++  java
  • 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)

    之前看内部类的时候没发现这个问题,今天写代码的时候遇到,写个最简单的例子:

    下面这一段代码

    红色的部分就是编译报错:

    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

    仅仅记录编程中遇到的问题。

  • 相关阅读:
    按钮设计
    图标设计
    滤镜与通道
    路径、形状工具与选区
    类的无参方法
    类和对象
    阅读器关闭时尝试调用Read无效时的解决方法
    进入ASP .net mvc的世界
    linux命令-vim
    linux命令-分区表fstab
  • 原文地址:https://www.cnblogs.com/tina-smile/p/5243747.html
Copyright © 2011-2022 走看看