1 package cspuzzles; 2 3 class SuperClass2 { 4 protected int x = 5; 5 6 { x++;} 7 8 public SuperClass2(){ 9 this(2); 10 x++; 11 } 12 13 public SuperClass2(int i){ 14 x *= i; 15 } 16 17 { x *= 2; } 18 } 19 20 public class Post002 extends SuperClass2{ 21 22 { x ++; } 23 24 public Post002(){ 25 x++; 26 } 27 28 public Post002(int i){ 29 super(i); 30 x *= i; 31 } 32 33 public static void main(String[] args) { 34 Post002 p = new Post002(); 35 System.out.println(p.x); 36 p = new Post002(2); 37 System.out.println(p.x); 38 } 39 }The tricky parts here are initialization blocks. Lines 6, 17, 22 are initialization blocks. An initialization block runs after the super constructors have run. If there is more than one initialization block, they are run in the same order as they appear in the class. Usually, initialization blocks are placed at the beginning of classes, but nothing stop us from writing one at the end of classes or in between methods.
The code prints:
27
50
The following table shows the lines executed for each of the objects created:
new Post() | new Post(2) |
Line 4: x = 5 | Line 4: x = 5 |
Line 6: x = 6 | Line 6: x = 6 |
Line 17: x = 12 | Line 17: x = 12 |
Line 14: x = 24 | Line 14: x = 24 |
Line 10: x = 25 | |
Line 22: x = 26 | Line 22: x = 25 |
Line 25: x = 27 | |
Line 30: x = 50 |
Do you think initialization blocks are useful? How have you used them? Share your thoughts in the comments.
No comments:
Post a Comment