Good day. Tell me please. There is a code:

public class A { public static int a = 0; public int b = 0; public A() { this.b = a++; } public static int get() { return new A().b + a; } public static void main(String[] args) { System.out.println(get()); System.out.println(get()); System.out.println(get()); } } 

Please tell me why this line is compiled:

 return new A().b + a; 

After all, the get () method is declared as static, which means that it can only work with static fields? Explain, please.

    2 answers 2

    And why he does not work. There are no problems with this - this field is static.

    But the appeal to the field b at first glance looks strange. But the fact is that this field is not addressed directly - but through the creation of a new object. And there is no prohibition on calling a constructor from a static method.

    • Tell me where to find the rules for static methods. looked here docs.oracle.com/javase/specs/jls/se7/html/… , but found nothing sensible? - Drylozav
    • and what rules do you want to see? they say "you can call the designer"? But I thought it was clear, otherwise no program would work. After all, the main method that runs everything - main - is static. Documentation is nice. But I think it is better to read a good book. - KoVadim
    • I mean, A (). B is a way to refer to a field b. But after all the field b field itself is not static. And how this challenge passes is not clear to me. - Drylozav
    • An instance of class A ( new A() ) is created and a call is made to the field b this instance. - Nofate

    in the static get () method, you create a new object of class A, after which it is possible to access non-static members of class A through a newly created object. Ie, in the get method, you create a temporary object, which is destroyed immediately after the fulfillment of its responsibility to change the variable a.

    Ie you have a class:

     public class SomeClass { static Class nameclass = new Class(); // Статический - значит общий объект для всех экземпляров SomeClass будь их хоть тысяча, все равно оги будут иметь общее поле nameclass, да и при отсутствии объектов SomeClass nameclass все равно существует ... // другие методы и поля } /*где-то внутри другого класа вы можете обратиться к nameclass без создания объекта SomeClass(одно из применений static)*/ SomeClass.nameclass.someMethodOfClass(); // Создаем 2 объекта класса SomeClass ob1 = new SomeClass(); ob2 = new SomeClass(); // Предположим у класса Class есть поле someValue равное 0 на данный момент ob1.nameclass.someValue = 100500; System.out.println(ob2.nameclass.someValue); // выведет 100500, а если бы nameclass был не статический, мы получили бы 0 

    This is the second use of static: for ob1 and ob2 nameclass is a common variable, changes in which from one object are immediately visible from another.

    • I cannot understand this static at all. so what is this static Class nameclass = new Class ()? How can an instance of a class be static? And most importantly, why? An example taken from Java Philosophy - Drylozav
    • Thank you very much for the clarification. Even in the specification could not find this. This philosophy is difficult for me (plus I'm still trying to read the original). Tell me, why is it even necessary? Is this a way to create an instance of a class somewhere? - Drylozav
    • Yes, this method is used to create singletones - objects that must exist in a single copy. But usually static classes cause leaks (at least in the android). - KoVadim
    • The main use of static in Java is the use of static methods in various libraries, for example, standard Math uses only static methods: class Math {public static long round (double a); public static int abs (int a); ...} // In the program we call these methods directly, without first creating an instance of Math, which is not needed at all double val1 = Math.round (Math.abs (val2)); - MDJHD