zoukankan      html  css  js  c++  java
  • 创建Java内部类的编译错误处理

    转自:http://www.cdtarena.com/javapx/201305/8712.html

      在创建非静态内部类时,经常会遇到“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”这个编译报错了。

  • 相关阅读:
    node express 上传文件
    [Java] 对象转型-01
    [Java] 类的Equals方法 (String, Data类都已经自动重写)
    editor does not contain a main type" 错误解决方
    Ubuntu网络连接图标消失解决方法
    [面试] 从尾到头打印链表-递归实现
    C++继承的例子 (1)
    国内访问gmail
    [python] 第7章 函数 第8章 模块
    Devcpp(Dev C++)使用说明及技巧
  • 原文地址:https://www.cnblogs.com/cdtarena/p/3108194.html
Copyright © 2011-2022 走看看