目录

一、错误代码和错误现象

先记录下问题现象,写java代码时遇到下面的编译错误。

no enclosing instance of type filetree is accessible. must qualify the 
allocation with an enclosing instance of type filetree (e.g. x.new a() 
where x is an instance of filetree).

代码如下:

import java.util.arrays;
import java.util.linkedhashmap;

public class filetree {
 class node {
  string name;

  public node(string name) {
   super();
   this.name = name;
  }

  linkedhashmap<string, node> map = new linkedhashmap<string, node>();
 }

 public static void outputthreeformat(string[] in) {
  arrays.sort(in);
  node root = new node("/");

 }

 public static void main(string[] args) {
  string[] in = { "usr/local/lib64", "games",
    "usr/drivers", "home", "var/log/" };
  outputthreeformat(in);

 }

}

错误截图如下:

二、如何解决这些错误

错误的含义是,没有可以访问的外部实例enclosing instance。必须分配一个合适的外部类filetree的实例(如x.new a(),x必须是filetree的实例。)

结合出错的代码,很容易知道根源是什么:

  • class node是非静态内部类
  • public static void outputthreeformat(string[] in)是静态方法
  • 静态方法是不能直接访问非静态类的。

1、可以不使用内部类

可以把class node作为外部类定义,这样在filetree类中不管是静态还是非静态方法都可以直接new node初始化个节点。

import java.util.arrays;
import java.util.linkedhashmap;

class node {
 string name;

 public node(string name) {
  super();
  this.name = name;
 }

 linkedhashmap<string, node> map = new linkedhashmap<string, node>();
}

public class filetree {

 public static void outputthreeformat(string[] in) {
  arrays.sort(in);
  node root = new node("/");

 }

 public static void main(string[] args) {
  string[] in = { "usr/local/lib64", "games", "usr/drivers", "home", "var/log/" };
  outputthreeformat(in);

 }

}

2、可以使用静态内部类

可以把class node作为静态内部类定义,即static class node

import java.util.arrays;
import java.util.linkedhashmap;

public class filetree {
 static class node {
  string name;

  public node(string name) {
   super();
   this.name = name;
  }

  linkedhashmap<string, node> map = new linkedhashmap<string, node>();
 }

 public static void outputthreeformat(string[] in) {
  arrays.sort(in);
  node root = new node("/");

 }

 public static void main(string[] args) {
  string[] in = { "usr/local/lib64", "games",
    "usr/drivers", "home", "var/log/" };
  outputthreeformat(in);

 }

}

3、使用非静态内部类时,使用外部类的实例进行调用

如下所示:

import java.util.arrays;
import java.util.linkedhashmap;

public class filetree {
 class node {
  string name;

  public node(string name) {
   super();
   this.name = name;
  }

  linkedhashmap<string, node> map = new linkedhashmap<string, node>();
 }

 public static void outputthreeformat(string[] in) {
  arrays.sort(in);
  filetree ft=new filetree();
  node root = ft.new node("/");

 }

 public static void main(string[] args) {
  string[] in = { "usr/local/lib64", "games",
    "usr/drivers", "home", "var/log/" };
  outputthreeformat(in);

 }

}

到此这篇关于解决java变异出现错误no enclosing instance of type xxx is accessible的文章就介绍到这了,更多相关解决java错误no enclosing instance of type xxx is accessible内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!