what does it meant that one instance of a static member exists? | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis
0

what does it meant that one instance of a static member exists?

13th Feb 2017, 8:26 AM
BHAGYA VIJAYAN
1 Resposta
+ 1
Take the example of this code: public class HelloWorld{ public static void main(String []args){ Example x = new Example(); Example y = new Example(); System.out.println(x.getCount()); System.out.println(y.getCount()); y.destroy(); System.out.println(x.getCount()); System.out.println(y.getCount()); y = null; } } class Example{ private static int instanceCount = 0; // static member Example() { instanceCount++; } int getCount() { return instanceCount; } void destroy() { try { this.finalize(); } catch (Throwable e) { e.printStackTrace(); } finally { instanceCount--; } } } Here the static member instanceCount is shared from all instances of the Example class. In the main method we created 2 different instances of the Example class (x and y). When those instances are instantiated the static member variable instanceCount is incremented. In fact if we created more it would be incremented with each new instance when the constructor is called. Now, when we call the getCount() method from either instance (x or y) we will receive the same (current) count of instances of the Example class (2), instead of each class having its own instanceCount variable with a count of 1 each.
13th Feb 2017, 10:35 AM
ChaoticDawg
ChaoticDawg - avatar