S
S
Sland Show2018-02-02 14:21:41
Java
Sland Show, 2018-02-02 14:21:41

How to determine the order of initialization of object properties, depending on different situations and context?

The question is quite simple, as many may think.
Generally:

abstract class A {
    int a = 8;

    public A() {
        show();
    }

    abstract void show();
}

class B extends A {
    int a = 90;

    void show() {
        System.out.println("" + a);
    }


}

And in the main method I create an object of class B:
public static void main(String args[]) { 
         new B(); // output - 0
}

It is understandable, the superclass constructor will call the polymorphic version of the show method (especially in the base class it is abstract). The context of the variable a will change (the one in class B has not yet been initialized with the value 90, because this happens in the constructor?). But after all, first, when creating an object B, its parent must be initialized, all the fields that are there. When, then, does the JVM have time to initialize the a field to zero if the superclass constructor is called first?
And in general, if you change the code in class B a little:
class B extends A {
    int x = 90; // поменял название переменной!

    void show() {
        System.out.println("" + a); // 8
    }

That will print the value of the variable a from the context of the object A - 8. Here I can somehow understand that the initialization of the variable occurs before the show function is called. Something like that:
public A() {
       super(); // Вызов конструктора Object`а
        a = 8;
        show();
    }

But when does it have time to initialize field a in the context of object B, if at all, JVM first works on its base class? And in general, are there subtleties here?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
mipan, 2018-02-02
@SlandShow

an int variable before initialization has the value 0;
Initialization:
Static fields of class Parent;
Static initialization block of the Parent class;
Static fields of the Child class;
Static initialization block of the Child class;
Non-static fields of the Parent class;
Non-static initialization block of the Parent class;
Parent class constructor;
Non-static fields of the Child class;
Non-static initialization block of the Child class;
Child class constructor.
Those. in the first variant, you display the value of the uninitialized variable of class B, and in the second, the already initialized variable from A.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question