Java 非静态方法可以';不能从静态上下文引用

Java 非静态方法可以';不能从静态上下文引用,java,Java,每当我尝试调用一个方法时,它都会给我错误 无法从的静态上下文引用非静态方法 我尝试在main中创建对象,并将它们作为参数发送给该方法,但也不起作用 您需要类的实例来从静态方法访问(调用)非静态方法。非静态方法或实例方法仅限于类的内部 下面是描述它的简单示例: class Test { public void nonStaticMethod() { } public static void main(String[] args) { Test t = new Test(); //you need

每当我尝试调用一个方法时,它都会给我错误

无法从的静态上下文引用非静态方法


我尝试在main中创建对象,并将它们作为参数发送给该方法,但也不起作用

您需要类的实例来静态方法访问(调用)非静态方法。非静态方法或实例方法仅限于类的内部

下面是描述它的简单示例:

class Test {
public void nonStaticMethod() {
}
public static void main(String[] args) {
Test t = new Test(); //you need to create an instance of class Test to access non-static methods from static metho
t.nonStaticMethod();
}

}

常规方法在创建对象时实例化,但
静态方法不需要。如果您使用的是
static
方法,则无法保证非静态方法已实例化(即可能没有创建
对象),因此编译器不允许使用它。

main
是静态方法<代码>公共静态void main(字符串[]args)

从静态方法或块可以访问任何其他静态方法以及静态实例。如果要访问非静态方法或实例,必须创建对象并通过引用进行访问

public class Test{
    public static void main(String[] args){
        print();// static method call
        Test test = new Test();
        test.print();// non static method call
    }
    public void print() {
        System.out.println("Hello non static");
    }
    public static void print() {
        System.out.println("Hello static");
    }
}

你可能想在这方面做进一步的阐述,你的问题是?此外,这是一个相当基本的问题-从这里开始:。请在谷歌上提供代码搜索,并从一个好的教程开始。Oracle教程将是一个很好的起点。
public class Foo {
    public static void main(String[] args) {
        Foo foo = new Foo();
        foo.print();
    }
    public void print() {
        System.out.println("Hello");
    }   
}