创建Java内部类的编译错误处理

    请大家尊重劳动成果,转载注明出处:http://blog.csdn.net/caoshichao520326/article/details/8961297

    在创建非静态内部类时,经常会遇到“No enclosing instance of type * is accessible. Must qualify the allocation with an enclosing   instance of type *(e.g. x.new A() where x is an instance of *).”这样的报错,其实原因只有一点,内部类是依赖于外部类存在的,所以在使用非静态内部类时,要求先实例化外部类才可以使用内部类。关于非静态内部类,我们可以把它理解成外部类的成员变量,我们在使用一个类的非静态成员变量时要求先对类进行实例化,然后通过对象来调用这个类的非静态成员变量。这里非静态内部类同外部类的关系,就如同非静态成员变量同类的关系一样。所以在使用非静态内部类时,要求先实例化外部类。

    下面我给出例子来分析一下:

package com.csc.innerclasstest;
/**
 * 
 * @author csc
 *
 */
//外部类
public class OuterClass {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		InnerClass innerClass = new InnerClass();
		innerClass.say();
		System.out.println("I am in OuterClass!");
	}
	
	//定义一个内部类
	private class InnerClass{
		
		private void say() {
			System.out.println("I am in InnerClass!");
		}
	}

}

     上面的代码的第16行将会报出“No enclosing instance of type OuterClass is accessible. Must qualify the allocation with an enclosing instance of type OuterClass (e.g. x.new A() where x is an instance of OuterClass).”这样的编译错误。错误的原因如上面红色字体所述。

解决方法一:将非静态内部类转换成静态内部类,即在上面程序的第21行的“Private”后面加上“Static”即可。

解决方法二:先实例化外部类,然后通过外部类来调用内部类的构造函数,代码如下:

package com.csc.innerclasstest;
/**
 * 
 * @author csc
 *
 */
//外部类
public class OuterClass {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		//实例化外部类
		OuterClass outerClass = new OuterClass();
		//通过外部类引用内部类
		InnerClass innerClass = outerClass.new InnerClass();
		innerClass.say();
		System.out.println("I am in OuterClass!");
	}
	
	//定义一个内部类
	private class InnerClass{
		
		private void say() {
			System.out.println("I am in InnerClass!");
		}
	}

}

    上面代码的第16行先进行了外部类的实例化,第18行通过外部类来引用内部类,这样就不会出现“No enclosing instance of type OuterClass is accessible. Must qualify the allocation with an enclosing instance of type OuterClass (e.g. x.new A() where x is an instance of OuterClass”这个编译报错了。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值