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”这个编译报错了。

  • 相关阅读:
    iReaper
    展望未来,总结过去10年的程序员生涯,给程序员小弟弟小妹妹们的一些总结性忠告(turn)
    用C#写ExtJS代码的开源工具extsharp
    如何你是公司的HR,去招聘asp.net程序员,你会对前来面试的人问什么问题。
    ExtJS 3.0 Designer Preview (官方的IDE可视化工具)
    Asp.net ajax、Anthem.net、Ajax pro三大ajax框架那一种使用比较方便?易于配置?
    C#和ASP.net程序员招聘技能要求
    序列化上面创建的Person对象,使其成为一个JSON字符串
    10大加速Ajax开发的框架
    android 解决wifi断线不稳定的问题终极办法
  • 原文地址:https://www.cnblogs.com/cdtarena/p/3108194.html
Copyright © 2011-2022 走看看