美文网首页安卓面试宝典
No enclosing instance of type Ma

No enclosing instance of type Ma

作者: itbird01 | 来源:发表于2021-11-24 07:02 被阅读0次

最近在刷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("调用了非静态方法");  
        }  
    }   
}  

相关文章

网友评论

    本文标题:No enclosing instance of type Ma

    本文链接:https://www.haomeiwen.com/subject/epywtrtx.html