me1*_*123 118 java static non-static
当我尝试在静态类中调用非静态方法时,我收到错误.
无法从类型回放中对非静态方法methodName()进行静态引用
我不能使方法静态,因为这也给我一个错误.
此静态方法无法从xInterface隐藏实例方法
有没有办法在另一个静态方法中调用非静态方法?(这两种方法分别是单独的包和单独的类).
Fab*_*eeg 89
您可以创建要在其上调用方法的类的实例,例如
new Foo().nonStaticMethod();
Run Code Online (Sandbox Code Playgroud)
小智 45
首先创建一个类Instance并使用该实例调用非静态方法.例如,
class demo {
public static void main(String args[]) {
demo d = new demo();
d.add(10,20); // to call the non-static method
}
public void add(int x ,int y) {
int a = x;
int b = y;
int c = a + b;
System.out.println("addition" + c);
}
}
Run Code Online (Sandbox Code Playgroud)
小智 10
public class StaticMethod{
public static void main(String []args)throws Exception{
methodOne();
}
public int methodOne(){
System.out.println("we are in first methodOne");
return 1;
}
}
Run Code Online (Sandbox Code Playgroud)
上面的代码没有执行,因为静态方法必须具有该类引用.
public class StaticMethod{
public static void main(String []args)throws Exception{
StaticMethod sm=new StaticMethod();
sm.methodOne();
}
public int methodOne(){
System.out.println("we are in first methodOne");
return 1;
}
}
Run Code Online (Sandbox Code Playgroud)
这肯定会被执行.因为在这里我们创建引用除了"sm"之外什么都没有,只使用那个类的引用,除了(StaticMethod=new Static method())之外我们正在调用方法one(sm.methodOne()).
我希望这会有所帮助.
听起来这个方法确实应该是静态的(即它不访问任何数据成员,并且它不需要调用实例).由于您使用了术语"静态类",我理解整个类可能专用于类似实用程序的方法,这些方法可能是静态的.
但是,Java不允许实现接口定义的方法是静态的.因此,当您(自然地)尝试使方法成为静态时,您将获得"无法隐藏实例方法"错误.(Java语言规范在第9.4节中提到了这一点:"请注意,接口中声明的方法不能声明为静态,否则会发生编译时错误,因为静态方法不能是抽象的.")
因此,只要该方法存在xInterface,并且您的类实现xInterface,您将无法使该方法成为静态.
如果您无法更改界面(或不想更改),您可以执行以下操作:
xInterface)和静态方法.实例方法将由一行代表静态方法组成.您需要包含非静态方法的类的实例.
就像当你尝试在没有实例的情况下调用类的非静态方法startsWith时String:
String.startsWith("Hello");
Run Code Online (Sandbox Code Playgroud)
你需要的是拥有一个实例,然后调用非静态方法:
String greeting = new String("Hello World");
greeting.startsWith("Hello"); // returns true
Run Code Online (Sandbox Code Playgroud)
所以你需要创建和实例来调用它.