Adn*_*ota 0 java methods static non-static
我有一个类,在其中我有一些静态和一些非静态方法,所以当我试图从静态方法访问非静态方法时,我得到了那个着名的错误.每当我在这个论坛上搜索时,我会在有两个课程的时候得到解决方案.我的问题是如果它们在同一个类中,如何从静态方法调用非静态方法?
我正在努力
new ClassName().methodName();
Run Code Online (Sandbox Code Playgroud)
但我的方法包含发送Intent和finish(),所以如果我创建其他对象而不是完成不起作用.
要从non-static method静态方法调用a ,必须首先instance of the class包含非静态方法.
非静态方法在类的实例上调用,而静态方法属于该类.
class Test
{
public static void main(String args[])
{
Test ot =new Test();
ot.getSum(5,10); // to call the non-static method
}
public void getSum(int x ,int y) // non-static method.
{
int a=x;
int b=y;
int c=a+b;
System.out.println("Sum is " + c);
}
}
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助.