问题
Im still new to java and i tried to create a inner class and call the method inside main. But theres a compilation error saying "Non static variable - This cannot be referenced from a static context"
Please help
class Class1{
public static void main(String args []){
Class2 myObject = new Class2();
myObject.newMethod();
}
public class Class2{
public void newMethod(){
System.out.println("Second class");
}
}
}
回答1:
An inner class needs a reference to an instance of the outer class in order to be constructed. If your class doesn't logically need that, then use the static
modifer to make it "just a nested class":
public static class Class2 {
public void newMethod(){
System.out.println("Second class");
}
}
EDIT: To create an instance of Class2
as an inner class, you could use something like:
Class1 outer = new Class1();
Class2 myObject = outer.new Class2();
Or more briefly:
Class2 myObject = new Class1().new Class2();
... but unless you really want a reference to an enclosing instance, it's much simpler to make the class just a nested class.
回答2:
make the inner class to be static by adding static keyword like
public static class Class2
then it should work. You can not ask anything static which are per class things in a non-static context. Alternatively you may access it by creating object without making the class2 as a static one.
回答3:
Inner class is accessed just like you access any other normal methods of your class.
So, just like you need a reference to an instance
of your class to access its method, similarly you need a reference to an instance of the outer class, to instantiate your inner class: -
Class1.Class2 myObject = new Class1().new Class2();
Or, an alternative is, you can make your inner class static
, in which case it is called a nested class
, then you can use your original way: -
public static class Class2{
public void newMethod(){
System.out.println("Second class");
}
}
回答4:
If you are novice to Java, next example may be helpful for you additionally.
"main()" is unsuitable for any complex logic. You cannot call from it any method that is not static in class. "main()" is nessesary only for starting of application,
In many cases first of all you need to create instance of class, that contains method "main". In example it is "OuterClass".
When instance of "OuterClass" exists, you have no problem to call from it anything dynamic, like your InnerClass methods of InnerClass object.
Here is an example:
public class OuterClass {
public static void main(String args []){
new OuterClass(); // Instance of First class
}
public OuterClass () { // constuctor
InnerClass myObject = new InnerClass();
myObject.newMethod();
}
public class InnerClass{
public void newMethod(){
System.out.println("Second class");
}
}
}
来源:https://stackoverflow.com/questions/12913731/inner-classes-in-java-non-static-variable-error