zoukankan      html  css  js  c++  java
  • java中"no enclosing instance of type * is accessible"的解决方法

    这种情况一般发生在“在静态方法里面使用内部类”

    测试代码:

    public class Test {
    	public static void main(String[] args) {
    		A a = new A(1);
    	}
    	class A {
    		int x;
    		public A() {}
    		public A(int x) {
    			this.x = x;
    		}
    	}
    }
    

      上面这份代码在main函数里面会发生编译错误,为了解决问题,让我们先看看编译器的提示:

    编译器告诉我们,没有可访问的Test类的实例,意味着下面将要使用实例,那个地方使用了呢?看后面的括号里面,"x.new A()",new A()实际上是x.new A(),其中x是Test的一个实例。所以我们可以先创建Test的一个实例,然后用这个实例的new方法new一个A()出来。

    于是可以改成下面的代码:

    public class Test {
    	public static void main(String[] args) {
    		Test test = new Test();
    		A a = test.new A(1);
    	}
    	class A {
    		int x;
    		public A() {}
    		public A(int x) {
    			this.x = x;
    		}
    	}
    }
    

      明白了这一点就可以解释下面的代码了:

    public class Test {
    	public static void main(String[] args) {
    		Test test = new Test();
    		A a = test.new A(1);
    		
    		B b = new B(2);//这里的B不是一个内部类,所以不存在上述问题所以可以直接写new
    		
    		A.AA aa = a.new AA(3);
    	}
    	class A {
    		int x;
    		public A() {}
    		public A(int x) {
    			this.x = x;
    		}
    		class AA {
    			int x;
    			AA() {}
    			AA(int x) {
    				this.x = x;
    			}
    		}
    	}
    }
    
    class B {
    	int x;
    	public B() {}
    	public B(int x) {
    		this.x = x;
    	}
    }
    

    或者用令外一种方法,将内部类改成静态的:

    public class Test {
    	public static void main(String[] args) {
    		A a = new A();
    	}
    	static class A {
    		int x;
    		public A() {}
    		public A(int x) {
    			this.x = x;
    		}
    	}
    }
    

      

  • 相关阅读:
    java ssh整合报错:java.lang.NoSuchMethodError: antlr.collections.AST.getLine()I
    Ubuntu16.04安装搜狗输入法后有黑边问题的解决方法
    socket
    vim编辑器的使用
    linux用户和群组
    bash shell
    [LightOJ 1128]Greatest Parent
    [Luogu P4180][BJWC 2010]严格次小生成树
    函数、方法区别
    有关_meta内容(持续更新)
  • 原文地址:https://www.cnblogs.com/jklongint/p/4977230.html
Copyright © 2011-2022 走看看