wood burning stoves 2.0*
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 Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "A confused result" Watch "A confused result" New topic

A confused result

Anon Ning

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

Process() {

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

Joined: Mar 09, 2001
Posts: 19
Thanks Michael! I got it.
I agree. Here's the link: http://aspose.com/file-tools
subject: A confused result
Similar Threads
Jtips #39
JTip Question
another strange question
overriding doubt