不能从静态 - 同一类调用非静态方法



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

我正在尝试

new ClassName().methodName(); 

但是我的方法包含发送 Intent 和 finish(),所以如果我正在创建其他对象而不是 finish 不起作用。

若要从静态方法调用non-static method,必须首先具有包含非静态方法的instance of the class

非静态方法称为 ON 类的实例,而静态方法属于类。

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);
   }
}

希望这有帮助。

最新更新