Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Static members (variables, functions, etc.) serve to allow callers of the class, whether they're within the class or outside of the class, to execute functions and utilize variables without referring to a specific instance of the class. Because of this, the concept of a "static local" doesn't make sense, as there would be no way for a caller outside of the function to refer to the variable (since it's local to that function).</p> <p>There are some languages (VB.NET, for example), that have a concept of "static" local variables, though the term "static" is inconsistently used in this scenario; VB.NET static local variables are more like hidden instance variables, where subsequent calls on the same instance will have the previous value intact. For example</p> <pre><code>Public Class Foo Public Sub Bar() Static i As Integer i = i + 1 Console.WriteLine(i) End Sub End Class ... Dim f As New Foo() Dim f2 as New Foo() f.Bar() // Prints "1" f.Bar() // Prints "2" f2.Bar() // Prints "1" </code></pre> <p>So, as you can see, the keyword "static" is not used in the conventional OO meaning here, as it's still specific to a particular instance of <code>Foo</code>.</p> <p>Because this behavior can be confusing (or, at the very least, unintuitive), other languages like Java and C# are less flexible when it comes to variable declarations. Depending on how you want it to behave, you should declare your variable either as an instance variable or a static/class variable:</p> <p>If you'd like the variable to exist beyond the scope of the function but be particular to a single instance of the class (like VB.NET does), then create an instance variable:</p> <pre><code>public class Foo { private int bar; public void Bar() { bar++; System.out.println(bar); } } </code></pre> <p>If you want it to be accessible to <em>all</em> instances of the class (or even without an instance), make it <code>static</code>:</p> <pre><code>public class Foo { private static int bar; public static void Bar() { bar++; System.out.println(bar); } } </code></pre> <p>(Note that I made <code>Bar()</code> static in the last example, but there is no reason that it has to be.)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload