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
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.
+ 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);
}
}
+ 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.
0
It must be, but what really unsurprising is an error message.
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.