How to use static member in class with Java

1 Answer

0 votes
public class MyClass {
    static int count = 0;

    MyClass() {
        count++;
    }

    static int getCount() {
        return count;
    }
    
    public static void main(String args[]) {
        MyClass c1 = new MyClass();
        MyClass c2 = new MyClass();
        MyClass c3 = new MyClass();

        System.out.println(MyClass.count);  
        
        System.out.println(c1.getCount()); 
        System.out.println(c2.getCount());  
        System.out.println(c3.getCount()); 
        
        MyClass c4 = new MyClass();
         
        System.out.println(MyClass.count);  
        
        System.out.println(c4.getCount()); 
    }
}




/*
run:

3
3
3
3
4
4

*/

 



answered Nov 14, 2023 by avibootz

Related questions

1 answer 173 views
1 answer 172 views
1 answer 176 views
1 answer 193 views
1 answer 165 views
...