• Register
+2 votes
6 views

Problem:

Learning a new programming language is really fun. So I am doing now. Yeah, java is fun but I stuck somewhere in static reference to the non-static method. What is this? I couldn’t figure it out properly. I have written a program below for a tet purpose but it throws an error: java cannot make a static reference to the non-static method

public class StaticReferenceToNonStatic{

   public static void myFirstMethod(){
      mySecondMethod(); 
   }
 
   public void mySecondMethod(){
   }
}

I just tried to call one of my functions inside another function. Any solution is much appreciated.
Thanks

ago by (4.8k points)  

1 Answer

+2 votes

Solution:

In java, static methods cannot call non-static methods. An instance of the class is required to call its methods and static methods are not associated with an instance (they are class methods). To fix it you have a few choices depending on your exact needs. I am just giving an example below to understand the error regarding your program.

public class StaticReferenceToNonStatic{
   public void myFirstMethod(){
      mySecondMethod(); 
   }

   public void mySecondMethod(){
   }
}

I hope you can figure out the difference between these two programs.

Thanks.

ago by (13.9k points)  
...