javaoopconstructor

Question about class members in Java


If I have a class SOmeClass, with a method someMethod, in the following code how does the compiler read the class member someConstant?

Class SomeClass{
            private int someConstant = someMethod(3); //3 is arbitrary

            private int anotherConstant;
            SomeClass(){
                 //constructor
                 anotherConstant = someConstant;
                     }

            public int someMethod(int an_int_value){
                 //something
                    return new_int;
                      }

This question is about my confusion of how compilers work. ANd how the machine reads code. The constant someConstant cannot be initiated until the class is instantiate, because the compiler needs to know what the method someMethod does. But the contructor can't be completed because anotherCOnstant needs to have this unknown value too. It seems to me (someone with no experience of computer science) that this is a catch-22 situation. This question is not limited to Java. It's just my most familiar language.


Solution

  • Object instantiation in Java is a multistep process. First, every field in the class is initialized to its default value (0, false, or null as appropriate). Next, each field with an initializer is, in order, initialized to this value. If this means calling any methods, then those methods are invoked with the fields either holding their default (if they haven't been touched yet) or the value they've been initialized to. Finally, the constructor is invoked.

    Notice that this means that the memory for the object is allocated before the constructor runs. This is necessary in order for this approach to work.