• 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Knute Snortum
  • Bear Bibeault
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Ganesh Patekar
Bartenders:
  • Frits Walraven
  • Carey Brown
  • Tim Holloway

A confused result

 
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • 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
  • 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
  • Quote
  • Report post to moderator
Thanks Michael! I got it.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!