This week's book giveaway is in the OCMJEA forum.
We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes A confused result Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "A confused result" Watch "A confused result" New topic
Author

A confused result

Anon Ning
Greenhorn

Joined: Mar 09, 2001
Posts: 19
hi all:
See this code:
class Process {
byte b=127;

Process() {
this.methodA();
}

void methodA() {
System.out.println("Value of b is = " +b );
}

public static void main(String [] args) {
Processor p = new Processor();
}
}

class Processor extends Process {
byte b=126;

Processor() {
System.out.println("Value of b* = " + b);
}

void methodA() {
System.out.println("Value of b** = " + this.b);
}
}
The output is :
Value of b**= 0 //(1)
Value of b*= 126
I was confused why line (1) is 0 rather than 126?
Please help me.Thanks!
Michael Burke
Ranch Hand

Joined: Jul 29, 2000
Posts: 103
The problem is because the call to methodA in class Process calls methodA in Processor but variable b in Processor hasn't been initialized yet. The order of initialization is super class first then sub-class. Since your still in the super class constructor Java hasn't gotten to the point where variables in the sub-class have been initialized. By the timee you get to the metehod call in the sub-class constructor the sub-class variables have been initialized. That's why the second call to methodA prints 126.
Anon Ning
Greenhorn

Joined: Mar 09, 2001
Posts: 19
Thanks Michael! I got it.
 
 
subject: A confused result