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?
Static Initializer
Moderator: admin
-
- Posts: 27
- Joined: Thu Feb 07, 2013 9:46 pm
- Contact:
-
- Site Admin
- Posts: 10066
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: Static Initializer
Are you sure 2 is printed twice?
If you like our products and services, please help us by posting your review here.
-
- Posts: 27
- Joined: Thu Feb 07, 2013 9:46 pm
- Contact:
Re: Static Initializer
Yes, 2 is printed twice.admin wrote:Are you sure 2 is printed twice?
-
- Site Admin
- Posts: 10066
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: Static Initializer
You are instantiating two instances of class B ( new B(10) and new B(15) and class B has an instance member A, which you are initializing as A a1 = new A(2);
In such cases, it is a good idea to use an IDE and run the program step by step.
In such cases, it is a good idea to use an IDE and run the program step by step.
If you like our products and services, please help us by posting your review here.
Who is online
Users browsing this forum: No registered users and 248 guests