• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

A confused result

 
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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!
 
Ranch Hand
Posts: 103
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 19
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Michael! I got it.
reply
    Bookmark Topic Watch Topic
  • New Topic