Friday, 18 April 2008

Super Sawal (question :D)

Hi today I saw a fantastic question of Static blocks,Initializer block and a constructor block.

see the question :

01: class Bird {
02: {
03: System.out.print("b1 ");
04: }
05:
06: public Bird() {
07: System.out.print("b2 ");
08: }
09: }
10:
11: class Raptor extends Bird {
12: static {
13: System.out.print("r1 ");
14: }
15:
16: public Raptor() {
17: System.out.print("r2 ");
18: }
19:
20: {
21: System.out.print("r3 ");
22: }
23:
24: static {
25: System.out.print("r4 ");
26: }
27: }
28:
29: class Hawk extends Raptor {
30: public static void main(String[] args) {
31: System.out.print("pre ");
32: new Hawk();
33: System.out.println("hawk ");
34: }
35: }

Output is: r1 r4 pre b1 b2 r3 r2 hawk

Think why???

If not scroll down :



Do not worry if you cannot understand it for first time. Copy it paste it in a notepad and run. I even could not understand it for first time.



Do you want easier version??
Yes.....Cool try this one then..

1. public class C extends B {
2. public static void main(String[] args) {
3. }
4. }
5. class B extends A {
6. static {
7. System.out.print("B1 ");
8. }
9. static {
10. System.out.print("B2 ");
11. }
12. }
13. class A {
14. static{
15. System.out.print("A ");
16. }
17. }

Predict the output: A B1 B2

Think why if not read...




When a class is having a Static block,initializer block and a constructor :

- Static blocks run first in order of Parent to Child class sequence.(Only one time when classes are loaded.)

- Initializer bocks run second in order of Parent to Child class sequence.(Every time when object of class is created.
Initializer bocks run do not run when the class is loaded

- constructor execute later in order of Parent to Child class sequence.(Every time when object of class is created.)

No comments: