0

I have a class and in it I have some static and some non-static methods so when I'm trying to access non-static methods from static ones I get that famous error. And whenever I am searching this forum I get solutions when there are two classes and from one you are trying to reach other one. My question is how to call non-static method from static one if they are in the same class?

I am trying with

new ClassName().methodName(); 

but my method contains sending of Intent and finish(), so if I'm creating other object than finish doesn't work.

Adnan Pirota
  • 299
  • 5
  • 25
  • 4
    Where the classes are makes no difference (in some rare cases it might). Concentrate on understanding what `static` members are. – Sotirios Delimanolis Nov 08 '13 at 14:36
  • If you attempted to call the non static `method` from a static context the question would be "which one". There could be thousands of objects of your class, each with its own `method` method – Richard Tingle Nov 08 '13 at 14:42
  • Imagine it like this. There is a factory with a Car blue print, now car has static methods like howManyCarsHaveBeenBuilt() but also non static methods like `accelerate()`. If you poke at the blueprint saying `accelerate()` which of the billion cars do you want to accelerate? – Richard Tingle Nov 08 '13 at 14:45

1 Answers1

5

To call a non-static method from a static method you must first have an instance of the class containing the non-static method.

A non-static method is called ON an instance of a class, whereas a static method belongs to 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);

   }
}

Hope this helps.

JNL
  • 4,683
  • 18
  • 29
  • But I am working in Android doesn't onCreate create an instance of the class ? – Adnan Pirota Nov 08 '13 at 15:02
  • 1
    onCreate(){} creates an instance of the Bundle, but not your class. `public void onCreate(Bundle savedInstanceState) {....}` – JNL Nov 08 '13 at 15:31