This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
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


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "explain" Watch "explain" New topic
Author

explain

Thomas Thomas
Greenhorn

Joined: Jun 17, 2003
Posts: 28
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

Joined: Nov 04, 2001
Posts: 1871
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

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
thomas
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: explain
 
Similar Threads
Constructors and inheritance
object resolution problem
mock exam question
to:rahul_mkar a. Yojana about protected variable
Super and sub class