File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes explain Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "explain" Watch "explain" New topic


Thomas Thomas

Joined: Jun 17, 2003
Posts: 28
class Super {
int a =f();
int f() {
return 1;

class Sub extends Super{
int b = 2;
int f() {
return b;

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

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

Joined: Nov 04, 2001
Posts: 1873
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...
Thomas Thomas

Joined: Jun 17, 2003
Posts: 28
Thanks a lot maulin...That did the trick and u really explained it. Really appreciate that..
Thanks a lot
I agree. Here's the link:
subject: explain
It's not a secret anymore!