Static methods in Java | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Static methods in Java

public class Counter { public static int COUNT=0; Counter() { COUNT++; } } public class MyClass { public static void main(String[ ] args) { Counter c1 = new Counter(); Counter c2 = new Counter(); System.out.println(Counter.COUNT); } } 1. How do I take away static so COUNT is each time 1? 2. Copied the whole program to my PC's notepad++. When compiling through cmd, it says that class Counter is public so it needs a separate file for it when printing javac

26th Mar 2017, 12:14 PM
Alex Snaidars
Alex Snaidars - avatar
5 Answers
+ 4
Take away static then you must access it by Counter object, and different Counter may have different COUNT. According to your codes now, if static is taken out, every Counter object instantiated will have COUNT of 1.
26th Mar 2017, 1:02 PM
Heng Jun Xi
Heng Jun Xi - avatar
+ 4
Like this? public class Counter { public int COUNT=0; Counter() { COUNT++; } } public class MyClass { public static void main(String[ ] args) { Counter c1 = new Counter(); Counter c2 = new Counter(); System.out.println(c1.COUNT); System.out.println(c2.COUNT); } }
26th Mar 2017, 1:18 PM
Heng Jun Xi
Heng Jun Xi - avatar
+ 4
If I am not mistaken, if a class is public it must be in its own Java file which is named with the class' name. Sololearn playground maybe handled the complexity for us.
26th Mar 2017, 2:11 PM
Heng Jun Xi
Heng Jun Xi - avatar
0
It must be, but what really unsurprising is an error message.
26th Mar 2017, 1:16 PM
Alex Snaidars
Alex Snaidars - avatar
0
Sure. Thank you. Don't you know why Code Playground compiles the program but PC does not? It seems that using keyword public on classes don't need to create a separate file here on SL.
26th Mar 2017, 1:48 PM
Alex Snaidars
Alex Snaidars - avatar