Skip to content Skip to sidebar Skip to footer

Cannot Make A Static Reference To The Non-static Method SendEmptyMessage(int) From The Type Handler

I have an error 'Cannot make a static reference to the non-static method sendEmptyMessage(int) from the type Handler' How to fix it? As I think this is a problem that this class wh

Solution 1:

"Cannot make a static reference to the non-static method sendEmptyMessage(int) from the type Handler"

This is due to the fact that Handler refers to a class, but sendEmptyMessage is not a static method (should be called on an object, and not on a class).

How to fix it?

To be able to call the sendEmptyMessage method you will either

  1. Need to instantiate a Handler, i.e., do something like

    Handler h = new Handler();
    h.sendEmptyMessage(0);
    

    or

  2. Add the static modifier to the sendEmptyMessage method:

    public static void sendEmptyMessage(int i) { ...
           ^^^^^^
    

Solution 2:

Handler handler = new Handler();
Handler.myStaticMethod();
handler.myNonStaticMethod();

In order to invoke a non-static method (aka instance methods) you must refer to a particular object (instance). You cannot refer to the class.

Static methods can be invoked by referencing only the class (they can also be called from a reference to an object of that class, but that is considered bad practice).

About usage: when you create an instance (object), that object has some inner data (state). Non static methods make use of the state of the object that is referenced, static methods do not need that data).


Post a Comment for "Cannot Make A Static Reference To The Non-static Method SendEmptyMessage(int) From The Type Handler"