Java中的内部类 - 非静态变量错误 [英] Inner classes in Java - Non static variable error
问题描述
我还是新的java和我试图创建一个内部类,并调用main里面的方法。
但是编译错误说非静态变量 - 这不能从静态上下文引用
请帮助
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);
}
}
}
类需要引用 outer 类的实例才能构建。如果你的类在逻辑上不需要它,那么使用 static
modifer使它只是一个嵌套类:
public static class Class2 {
public void newMethod(){
System.out.println(Second class);
}
}
编辑:创建 Class2
作为内部类,您可以使用类似:
Class1 outer = new Class1();
Class2 myObject = outer.new Class2();
或更简单:
Class2 myObject = new Class1()。new Class2();
...除非您真的需要 ,将类作为一个嵌套类简单得多。
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");
}
}
}
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.
这篇关于Java中的内部类 - 非静态变量错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!