No enclosing instance of type 类名 is accessible. Must qualify the allocation with an enclosing instan

本文探讨了在Java中从静态方法内部实例化非静态内部类的问题,并提供了解决方案,包括将内部类声明为静态或在动态上下文中实例化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

下面是我写的代码,一个经典的内部类

public class Value{
	public static void main(String[] args) {
		Test y=new Test();
	}
	class Test{
		public Test() {
			System.out.println("yes");
		}
	}
}
结果在编译阶段就报错了:

No enclosing instance of type Value(类名) is accessible. Must qualify the allocation with an enclosing instance of type Value (e.g. x.new A() where x is an instance of Value).

没有可访问的内部类Value的实例,必须分配一个合适的内部类E的实例(如x.new A(),x必须是Value的实例。)

原来是因为我写的Value类是动态的,而public static void main方法是静态的,我们没办法在静态方法内去实例化一个动态对象
因此最简单的方法就是把class Test 换成 static class Test

或者在别的动态方法内调用动态方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值