What's the equivalent of C's “static” keyword in Java?

前端 未结 5 1660
粉色の甜心
粉色の甜心 2020-12-05 12:32

I want to know what could be the equivalent keyword in java which could perform same function as \"Static keyword in C\".. I want to do recursion in java, performing same fu

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-05 13:10

    The "static" keyword in C actually serves two functions depending on where it's used. Those functions are visibility and duration (these are my terms based on quite a bit of teaching, the standard, if you're interested in that level of detail, uses different terms which I often find confuses new students, hence my reticence in using them).

    • When used at file level, it marks an item (variable or function) as non-exported so that a linker cannot see it. This is static as in visibility, duration is the same as the program (i.e., until the program exits). This is useful for encapsulating the item within a single compilation unit (a source file, in its simplest definition). The item is available to the whole compilation unit (assuming it's declared before use).
    • When used within a function, it controls duration (visibility is limited to within the function). In this case, the item is also created once and endures until the program exits. Non-static variables within a function are created and destroyed on function entry and exit.

    I gather what you're after is the first type, basically a global variable since I can't immediately see much of a use for the other variant in recursion..

    It can't be done since, in Java, everything must belong to a class. The workaround is to create a class holding the "globals" and either:

    • pass that object around so you can reference its members; or
    • construct a singleton item so you can access its members.

提交回复
热议问题