可能重复:
"无法从静态上下文引用非静态方法"背后的原因是什么?
无法对非静态方法
进行静态引用,无法对非静态字段进行静态引用
我无法理解我的代码有什么问题.
class Two {
public static void main(String[] args) {
int x = 0;
System.out.println("x = " + x);
x = fxn(x);
System.out.println("x = " + x);
}
int fxn(int y) {
y = 5;
return y;
}
}
Run Code Online (Sandbox Code Playgroud)
线程"main"中的异常java.lang.Error:未解决的编译问题:无法对类型为2的非静态方法fxn(int)进行静态引用
Kep*_*pil 38
由于main方法是static,而fxn()方法不是,因此无需先创建Two对象即可调用该方法.因此要么将方法更改为:
public static int fxn(int y) {
y = 5;
return y;
}
Run Code Online (Sandbox Code Playgroud)
或将代码更改main为:
Two two = new Two();
x = two.fxn(x);
Run Code Online (Sandbox Code Playgroud)
static在Java教程中阅读更多内容.
您无法访问方法 fxn,因为它不是静态的。静态方法只能直接访问其他静态方法。如果要在 main 方法中使用 fxn,则需要:
...
Two two = new Two();
x = two.fxn(x)
...
Run Code Online (Sandbox Code Playgroud)
也就是说,创建一个双对象并调用该对象上的方法。
...或使 fxn 方法静态。
您不能从静态方法引用非静态成员。
非静态成员(如 fxn(int y))只能从类的实例中调用。
例子:
你可以这样做:
public class A
{
public int fxn(int y) {
y = 5;
return y;
}
}
class Two {
public static void main(String[] args) {
int x = 0;
A a = new A();
System.out.println("x = " + x);
x = a.fxn(x);
System.out.println("x = " + x);
}
Run Code Online (Sandbox Code Playgroud)
或者您可以将方法声明为静态。
| 归档时间: |
|
| 查看次数: |
131070 次 |
| 最近记录: |