Learning Java by Building Android  Games
上QQ阅读APP看书,第一时间看更新

Static methods

We know quite allot about classes; how to turn them into objects and use their methods and variables. But something isn't quite right? Since the very start of the book, we have been using a class that doesn't conform to everything we have learned in this chapter- so far. We have used Log to output to the logcat window, but have not instantiated it once! How can this be?

The static methods of classes can be used, without first instantiating an object of the class.

Tip

We can think of this as a static method belonging to the class and all other methods belonging to an object or an instantiation of a class.

And as you have probably realized by now, Log contains static methods. To be clear: Log contains static methods but Log is still a class.

Classes can have both static and regular methods as well, but the regular methods would need to be used in a regular way, via an instance of the class.

Take another look at Log.d in action.

Log.d("Debugging","In newGame");

Here, d is the method being statically accessed and the method takes two parameters, both of type String.

Note

More uses for the static keyword

The static keyword also has another consequence, for a variable especially when it is not a constant (can be changed) and we will see this in action in our next mini-app.

Static methods are often provided in classes which have uses that are so generic it doesn't make sense to have to create an object of the class. Another useful class with static methods is Math. This class is a part of the Java API, not the Android API.

Tip

Want to write a calculator app? It's easier than you think with the static methods of the Math class. You can look at them here: http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html

If you try this out you will need to import the Math class, the same way you imported all the other classes we have used.