Error in a static method in a inner class [duplica

2019-09-16 09:15发布

问题:

This question already has an answer here:

  • Why can't we have static method in a (non-static) inner class? 14 answers

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

on this code

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();
    }

}

and i cant understand why!

回答1:

Refer to the documentation here.

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.



回答2:

Class2 is an inner class which means that it needs to be tied to an Class1 object. Then objects of Class2 can access the fields of the bound object at all times:

public class Class1 {

    private String name = "class1";

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

    class Class2 {
        public void show() {
            System.out.println("helloworld: "+name); //accessing the name field of a without needing the variable
        }
    }

}

or you need to make Class2 static so it doesn't need the Class1 instance.

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

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

}


回答3:

Class C2 in your example above is a local Inner class, which means an inner class defined within a method of an outer class, and such classes cannot have static methods inside them because they are associated with objects, (static methods are not dependent upon objects).

Moreover, a local inner class must be instantiated within the method it has been created and not outside the method. This is a rule.

try modifying your code in following way:

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

public static void show() { 
    class C2 { 

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

    C2 obj= new C2();
obj.hello();
}

}

This should work.



回答4:

You cant do this since you need to create an instance of Class 'Class1' before you can access Class 'C2'. However the method 'hello' should be possible to access without creating an instance (being a static method).