Lets have an example of below classes:



Explanation:
A a = new A();
since new A object instance is created, and the static members loads when the class loads in the memory,
A's Static constructor will be called first.
then, A's public constructor will be called.

A c = new B();
Since new B object instance is created, but the reference is of A. The static constructor of B will be called first followed by A's static one. Then A's public constructor and B's public constructor will be called.

B d = new B();
Since new B object instance is created, the result will be same as above.

Similarly, if in the given scenario, there will be no static constructor defined in either of the classes, then static constructors calls would not be there in the result and the output would have followed the same sequence.
Explanation:
A a = new A();
since new A object instance is created, and the static members loads when the class loads in the memory,
A's Static constructor will be called first.
then, A's public constructor will be called.
A c = new B();
Since new B object instance is created, but the reference is of A. The static constructor of B will be called first followed by A's static one. Then A's public constructor and B's public constructor will be called.
B d = new B();
Since new B object instance is created, the result will be same as above.
Similarly, if in the given scenario, there will be no static constructor defined in either of the classes, then static constructors calls would not be there in the result and the output would have followed the same sequence.
No comments:
Post a Comment