2018/01/02常见异常处理

1)自己自作主张改写的原站长[武器类Weapon(继承类Item)]的代码案例如下:

 1 /**
 2  * Description
 3  * <br> this's a test class
 4  * Created by test on 2018/01/02
 5  * @author peaceful water
 6  *
 7  */
 8 public class Hero {
 9     public  class Weapon {
10         int damage;//多了一个属性
11         String name;
12         int price;
13     }
14     public static void main(String[] args) {
15         Weapon infinityEdge = new Weapon();
16         infinityEdge.damage = 65; //damage属性在类Weapon中新设计的
17         
18         infinityEdge.name = "无尽之刃";//name属性,是从Item中继承来的,就不需要重复设计了
19         infinityEdge.price = 3600;
20     }
21 }

出现异常提示:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    No enclosing instance of type Hero is accessible. Must qualify the allocation with an enclosing instance of type Hero (e.g. x.new A() where x is an instance of Hero).

    at Hero.main(Hero.java:19)

解决方法:将第9行代码修改为:public static class Weapon。

原因如下:起初写的内部类Weapon是动态的,也就是开头以public class开头。而主程序是public static class main[即静态方法]。在Java中,类中的静态方法不能直接调用动态方法。只有将某个内部类修饰为静态类,然后才能够在静态类中调用该类的成员变量与成员方法。所以解决办法是将public class改为public static class.

参考链接:Java出现No enclosing instance of type E is accessible. Must qualify the allocatio

posted on 2018-01-02 11:23  梧桐雨与荔枝  阅读(150)  评论(0编辑  收藏  举报

导航