• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

explain

 
Thomas Thomas
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class Super {
int a =f();
int f() {
return 1;
}
}

class Sub extends Super{
int b = 2;
int f() {
System.out.println("Print");
return b;
}
}

public class Test7 {
public static void main(String[] args) {
Super sup = new Sub();

System.out.println(sup.a);
System.out.println(sup.f());
}
}
The output is print 0 print 2
I hope the first print is happening during the intialization of the variable : a but it is not assigned the value 2.please explain instance intializer.
 
Maulin Vasavada
Ranch Hand
Posts: 1873
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi Thomas
here is what happens here.
when u create object of type Sub() then
1. the default (no-arg) constructor gets called for Sub
2. super() is called from Sub's default constructor
3. int a tries to get initialized where f() is called
4. as f() is overridden, the Sub's f() gets called which returns 'b' BUT so far 'b' is not initialized as 2 due to the init sequence i mention below so the default int value 0 is returned for b and int a becomes 0
5. so when u call S.o.p(sub.a) it prints 0
6. but when the super() call returns to the Sub's constructor then the int b of Sub gets initialized to 2 so when u do s.o.p(sub.f()) then it prints 0
the sequence of initialization,
1. static vars
2. static initialization blocks
3. super() call gets resolved (if there is this() call then that gets executed)
4. instance vars
5. instance initialization blocks
6. rest of the constructor
here, u can predict one mis-behavior. in ur code b was a 'int' var. so the default value was 0 but if it were a reference type then it would have been null and if in the parent u tried to invoke a method on that reference then u'd run into NullPointerException...
i hope i'm able to explain it...
regards
maulin
 
Thomas Thomas
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot maulin...That did the trick and u really explained it. Really appreciate that..
Thanks a lot
thomas
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic