In the public class there is a static field that I dream to modify (increment by one) if the number of class objects increases.

 public class Man{ private static int allMans = 0; public void addMoreMans() { this.allMans++; } public static void main(String[] args){ Man man = new Man(); man.addMoreMans(); } } 

It does not work. Oh yes! Integer allMans static, what this !? I appeal through Man.allMans also does not want. And how to contact him?

  • Just allMans++; ? - YurySPb
  • 2
    Read the theory ... Static variables are tied to a class, not to its instances; therefore, they are not referred to as object fields — the object name is a point field name, but as a class field — the class name is a point field name. So you can get access outside the class, if, of course, allow access modifiers. And within the class it is enough to do as shown in the previous comment - just the name of the field. - Dmitry

1 answer 1

In fact, all the options should work if the main method is in the same class.

 public class Man{ private static int allMans = 0; public void addMoreMans() { allMans++; Man.allMans++; this.allMans++; } public static void main(String[] args){ new Man().addMoreMans() ; System.out.println(Man.allMans); } } 

the result is as follows: 3

But if you have a main method in another class for example:

 public class Mans { public static void main(String[] args){ Man m =new Man() ; m.addMoreMans(); System.out.println(Man.allMans); } } 

Here you will not get access to allMans as you have a private variable. If you change to

  public static int allMans = 0; 

here and there everything will work for you.