0

STATIC. need explanation of this code

public class Counter { public static int COUNT=0; Counter() { COUNT++; } public static void main(String[] args) { Counter obj1 = new Counter(); Counter obj2 = new Counter(); System.out.println(Counter.COUNT); } } I understood that the objects of the particular class share static variable which belongs to the class. But println method can access it. So static means that other methods in the main method can access it, right? Then what is difference between public and static? Thanks in advance.

5th Jul 2017, 11:41 AM
Bekzod Hakimov
Bekzod Hakimov - avatar
3 Respuestas
+ 1
If COUNT wasn't static : Counter obj1 = new Counter(); // COUNT==1 Counter obj2 = new Counter(); // COUNT==1 Because COUNT would be initialized every time an new object is created.
5th Jul 2017, 12:13 PM
Jojo
+ 1
public private protected and default these are access modifiers and they has nothing to do with static.. static is a keyword used for creating class methods and variables these exist independently of any instance created for the class
5th Jul 2017, 12:15 PM
Мг. Кнап🌠
Мг. Кнап🌠 - avatar
0
No no no! Static means the variable is initialized only one time (the first time it's evaluated). Here, COUNT will be incremented each time a new object will be created. Counter obj1=new Counter(); // COUNT==1 Counter obj2= new Counter (); // COUNT==2...
5th Jul 2017, 12:11 PM
Jojo