No enclosing instance of type Main is accessible. Must qualify the allocation with an enclosing i...

本文介绍了在使用Java内部类时遇到的一个常见错误:No enclosing instance of type Main is accessible. Must qualify the allocation with an enclosing instance of type Main. 分析了错误原因,并提供了两种解决方案:一是将内部类改为静态类;二是将内部类提升为外部类。

最近在刷AC,在编译时出现:

No enclosing instance of type Main is accessible. Must qualify the allocation with an enclosing instance of type Main (e.g. x.new A() where x is an instance of Main).
提示截图.png

根据提示,没有可访问的内部类的实例,必须分配一个合适的内部类的实例(如x.new A(),x必须是内部类的实例。看着这句提示,我。。。
郁闷中.png
我已经用new实例化了这个类,为什么还不行呢。

于是仔细看了一下IDE提示的地方,看了一下代码,突然发现,一般AC题目的时候,要求main方法是static的,而我写的Student内部类是非静态的,所以无法访问
错误截图.png

最简单的改法:将Student改为静态方法之后,不再报错。
这个错误很低级,将其总结,提醒自己,之后不可再错。

此处,我们引出另外一个知识点,Java静态方法访问非静态方法的实现方法有哪些?
不多说,直接上代码:

1) 将内部类修改,变为外部

class test{  
    public static void main(String args[]){           
       System.out.println(new test1().methodname());         
    }     
}  


class test1{  
    public String methodname(){  
        System.out.println("调用了非静态方法");  
    }  
}  

2) 将内部类修改为静态内部类

class test{  
    public static void main(String args[]){           
       System.out.println(new test1().methodname());         
    }    

    public  class static  test1{  
        public String methodname(){  
             System.out.println("调用了非静态方法");  
        }  
    }   
}  
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

itbird01

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值