This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes When do variables get initialization ?? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "When do variables get initialization ??" Watch "When do variables get initialization ??" New topic

When do variables get initialization ??

Chen SanHau

Joined: Feb 06, 2004
Posts: 27
When I run my code :

the result:
a in class A: 2
a,b (1)in class A: 2, 0
a,b (2)in class A: 2, 2
2, 2
My simple question is
a,b (1)in class A: 2, 0
a,b (2)in class A: 2, 2
Why they get difference values??
I need your help! Thanx!!
[ March 19, 2004: Message edited by: Ha LoHa ]
Anthony Yip
Ranch Hand

Joined: Aug 24, 2003
Posts: 30
When objA was created with new A(), since no argument provided, default constructor called and objA's variable a is assigned a value of 0, then nothing printed.
When objB was created with argument objA, the super(2) in class B's constructor called. As class B is subclass of Class A, super(2) call class A's constructor with an argument 2. And the variable a of objB is assigned a value of 2. Then, print the message " a in class A: 2 ".
After that, variable b is assigned a value equals to objA's variable a, that is 0. So, print "a,b (1)in class A: 2, 0".
Lastly, variable b is re-assigned a value equals to objB's variable a, that is 2. So, print "a,b (2) in class A: 2, 2".
The difference between the 2 statement is because b's value changed from value equals to objA's a to objB's a.
Is it clear?
Anthony Yip
I agree. Here's the link:
subject: When do variables get initialization ??
It's not a secret anymore!