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;
    		}
    	}
    }
    

      

  • 相关阅读:
    SSD
    NMS---非极大值抑制
    检测评价函数 IOU
    Ground Truth
    耿建超英语语法---状语从句
    联合索引创建时候的排序规则
    order by limit的原理
    mysql事务四种隔离级别
    为什么 Redis 快照使用子进程
    MYSQL查询~ 存在一个表而不在另一个表中的数据
  • 原文地址:https://www.cnblogs.com/jklongint/p/4977230.html
Copyright © 2011-2022 走看看