0

我有一个类,其中有一些静态方法和一些非静态方法,所以当我尝试从静态方法访问非静态方法时,我得到了那个著名的错误。每当我在这个论坛上搜索时,当有两个课程并且您试图从一个课程中找到另一个课程时,我都会得到解决方案。我的问题是如果它们在同一个类中,如何从静态方法调用非静态方法?

我正在尝试

new ClassName().methodName(); 

但我的方法包含 Intent 和 finish() 的发送,所以如果我创建的对象不是完成,则无法正常工作。

4

1 回答 1

5

要从静态方法调用 a non-static method,您必须首先拥有一个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);

   }
}

希望这可以帮助。

于 2013-11-08T14:37:14.623 回答