内部类中的静态方法中的错误 [英] Error in a static method in a inner class

查看:98
本文介绍了内部类中的静态方法中的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解内部类的工作原理,并在尝试一些简单的代码时遇到错误:The method hello cannot be declared static; static methods can only be declared in a static or top level type

Im trying to understand how inner class works and while experimenting with some simple code i got a error : The method hello cannot be declared static; static methods can only be declared in a static or top level type

关于此代码

public class Class1 {
    public static void main(String[] args) {
        Class1 c = new Class1();
        c.show();
    }

    public static void show() { 
        class C2 { 

            static public void hello() { 
                System.out.println("show class");
            }
        }

        C2.hello();
    }

}

我不明白为什么!

推荐答案

请参阅 内部类:与实例方法和变量一样,内部类与其所在类的实例相关联,并且可以直接访问该对象的方法和字段.另外,由于内部类与实例相关联,因此它本身不能定义任何静态成员.

Inner Classes: As with instance methods and variables, an inner class is associated with an instance of its enclosing class and has direct access to that object's methods and fields. Also, because an inner class is associated with an instance, it cannot define any static members itself.

这篇关于内部类中的静态方法中的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆