Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't use a public static method?

Tags:

java

android

This is confusing. I'm look at the Android 2.2.2_r1 source code for the NotificationManager class, and I see the method getService() which is defined as public and static. However, eclipse is telling me:

The method getService() is undefined for the type NotificationManager on the line

 Object o = NotificationManager.getService();

My project is building against Android 2.2/ API Level 8. I tried to use reflection to see the method names and modifiers, and sure enough, I got back

public static getService

Am I missing something here? Why would eclipse tell me this method doesn't exist?

like image 734
you786 Avatar asked Jul 28 '12 20:07

you786


People also ask

Why can't this be used in static methods?

The "this" keyword is used as a reference to an instance. Since the static methods doesn't have (belong to) any instance you cannot use the "this" reference within a static method.

Which Cannot be used in static method?

A static method cannot access a class's instance variables and instance methods, because a static method can be called even when no objects of the class have been instantiated. For the same reason, the this reference cannot be used in a static method.

Can we use static in public?

Use public static methods if the method can be considered a unit, and can be effectively tested on its own. It's plain hard to implement dependency injection or mocks on types that use static method. I use static methods for utility methods with few/no dependencies, and well defined input/output.

Can we override public static method in Java?

No, we cannot override static methods because method overriding is based on dynamic binding at runtime and the static methods are bonded using static binding at compile time. So, we cannot override static methods.


1 Answers

You will find a very detailed answer in this post.

In short: Because you compile against the android.jar, which has all hidden methods (like the one you are trying to access) removed. They will only be there on runtime, for internal android usage.


But since you perhaps also need it. The right way to access the NotificationManager is via the getSystemService method of a context:

NotificationManager nm = (NotificationManager)ctx.getSystemService(Context.NOTIFICATION_SERVICE);

With context being a valid context (like your current activity).

like image 75
Tim Roes Avatar answered Sep 30 '22 04:09

Tim Roes