2 scenarios to use the static modifier

utility-method-always-runs-the-same

Imagine you've got a utility class with a method that always runs the same way. It wouldn't matter which instance of the class performed the method—it would always behave exactly the same way. In other words, the method's behavior has no dependency on the state (instance variable values) of an object. So why, then, do you need an object when the method will never be instance-specific? Why not just ask the class itself to run the method?

keep-a-running-total-of-instances

Let's imagine another scenario: Suppose you want to keep a running count of all instances instantiated from a particular class. Where do you actually keep that variable? It won't work to keep it as an instance variable within the class whose instances you're tracking, because the count will just be initialized back to a default value with each new instance.

Static Variables and Methods


Variables and methods marked static belong to the class, rather than to any particular instance. In fact, you can use a static method or variable without having any instances of that class at all. You need only have the class available to be able to invoke a static method or access a static variable. static variables, too, can be accessed without having an instance of a class. But if there are instances, a static variable of a class will be shared by all instances of that class; there is only one copy.

A static method can't directly access a nonstatic (instance) variable, because there is no instance!

The same applies to instance methods; a static method can't directly invoke a nonstatic method.
Think static = class, nonstatic = instance.


Accessing Static Methods and Variables


The way we access a static method (or static variable) is to use the dot operator on the class name, as opposed to using it on a reference to an instance.

A syntax trick


This is a syntax trick to let you use an object reference variable to get to a static method or variable, but the static member is still unaware of the particular instance used to invoke the static member. In other words, the compiler cares only that reference variable is declared as which type.

redefine vs. override


Finally, remember that static methods can't be overridden! This doesn't mean they can't be redefined in a subclass, but redefining and overriding aren't the same thing. Let's take a look at an example of a redefined (remember, not overridden), static method: 
發佈了21 篇原創文章 · 獲贊 4 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章