Static Initializer
Posted: Fri Mar 01, 2013 11:38 am
Hi,
I have following code
public class A {
public A() { }
public A(int i) { System.out.println(i ); }
}
public class B {
static A s1 = new A(1);
A a1 = new A(2);
public B(int i)
{
System.out.println(i);
}
public static void main(String[] args){
B b1 = new B(10);
A a2 = new A(3);
}
static A s2 = new A(4);
static B b2 = new B(15);
}
The o/p from this program is
1
4
2
15
2
10
3
My doubt is why 2 is printed twice instead of once, as instance a1 should have initialized only once?
I have following code
public class A {
public A() { }
public A(int i) { System.out.println(i ); }
}
public class B {
static A s1 = new A(1);
A a1 = new A(2);
public B(int i)
{
System.out.println(i);
}
public static void main(String[] args){
B b1 = new B(10);
A a2 = new A(3);
}
static A s2 = new A(4);
static B b2 = new B(15);
}
The o/p from this program is
1
4
2
15
2
10
3
My doubt is why 2 is printed twice instead of once, as instance a1 should have initialized only once?