创建Java内部类的编译错误解决
发布时间:2021-11-21 17:05:06 所属栏目:PHP教程 来源:互联网
导读:在创建非静态内部类时,经常会遇到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 *).这样的报错,其实原因只有一点,内部类是依赖于外部类
在创建非静态内部类时,经常会遇到“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”这个编译报错了。 ![]() (编辑:应用网_丽江站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |