wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Constructor Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Constructor" Watch "Constructor" New topic
Author

Constructor

laoniu gougou
Greenhorn

Joined: Jan 25, 2001
Posts: 25
class Process {
byte b=127;

Process() {
this.methodA();
}

void methodA() {
System.out.println("Value of Super 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 Sub b = " + b);
}
}

The output after run is:
Value of Sub b = 0
Value of b = 126
Why seems methodA of Processor is invoked while b of Processor is not initialized?
Pam Doucette
Greenhorn

Joined: Mar 13, 2001
Posts: 27
I'm no expert, but this is what I think is going on.
call to new Processor() goes to instantiate a Processor object.
This object instantiation implicitly calls the superclass constructor.
The superclass constructor calls this.MethodA - but the object you are trying to instantiate is the Processor - so it calls the Processor's MethodA - before the Processor object has actually been constructed and instance variables have been assigned.
I added some comments to the code to demonstrate - but I could be wrong. Anyone have a better explanation?
class Process {
byte b=127;
Process() {
System.out.println("Process constructor initialized");
System.out.println("Value of b it " + b);
this.methodA();
System.out.println("Process constructor finished");

}
void methodA() {
System.out.println("Value of Super b is = " + b );
}
public static void main(String [] args) {
Processor p = new Processor();
}
}
class Processor extends Process {
byte b=126;
Processor() {
System.out.println("Processor constructor initialized");

System.out.println("Value of b = " + b);
System.out.println("Processor constructor finished");

}
void methodA() {
System.out.println("Value of Sub b = " + b);
}
}
Output is:
Process constructor initialized
Value of b is 127
Value of sub b = 0
Process constructor finished
Processor constructor initialized
Value of b = 126
Processor constructor finished
sajida kal
Ranch Hand

Joined: Mar 22, 2001
Posts: 89
Pam,
I also played around with the code and came to the same conclusion. I somehow did not expect the overridden method to be called when the superclass constructor was invoked. and here I was thinking I had grasped this concept quite well.
anyways, good question laoniu!
 
 
subject: Constructor