-1

Exactly when the Class members are initialized ?

In below code:

public class A{
    public  B b = new B();
    private C c = new C(123);

    public A (arg a){
        // Do something
    }

    public someMethod(){
       Log.i(TAG, " "+ b.getD());
    } 
}

main(){
    A a = new A ("xyz"); }

When would be the Object of Class B & C created? And is it guaranteed to be created?

Should a professional app use such code or not ?

Md. Armaan-Ul-Islam
  • 2,154
  • 2
  • 16
  • 20
  • Sorry. That post "https://stackoverflow.com/questions/23093470/java-order-of-initialization-and-instantiation" discusses the sequence while implementing an interface or extending a class/abstract class. My query is pretty much simpler and straight forward than that, which requires a simple answer :) – Md. Armaan-Ul-Islam Sep 12 '19 at 09:07

2 Answers2

2

When an object is created, the following things are done in the following order:

  1. The object is allocated on the heap with the correct object type, and all instance fields are "default initialized" to zero, false or null.
  2. The expressions in the super(...) or this(...) are evaluated and the constructor for the next class up the chain is called. (This recurses up the chain constructor, so that the Object constructor gets executed first.)
  3. The instance variable initializers and any instance initializer blocks are executed in order.
  4. The body of the constructor is executed.
  5. The constructor returns.

Hope it helps you.

Jakir Hossain
  • 3,830
  • 1
  • 15
  • 29
2

You can analyze the question this way:

class Scratch {
    public static void main(String[] args) {
        A a = new A ("xyz");
    }
}

class A{
    public  B b = new B();
    private C c = new C(123);

    public A (String a){
        System.out.println("new A()");
    }
}

class B {
    public B() {
        System.out.println("new B()");
    }
}

class C {
    public C(int i) {
        System.out.println("new C()");
    }
}

which executes giving the following output:

new B()
new C()
new A()

which matches wiith the answer of @Jakir Hossain.

So: inline fields initializers are executed before code in constructor, following the same order which they are declared in.

Instances of classes B and C are created on A's instance creation, before A's constructor is executed. This ordering (and fields' initialization) are guaranteed.

Pietro Martinelli
  • 1,776
  • 14
  • 16