wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes overriding doubt 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 "overriding doubt" Watch "overriding doubt" New topic
Author

overriding doubt

seema ram
Greenhorn

Joined: Feb 15, 2001
Posts: 3

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);
}
}
What is the Output?
1.Prints Value of b = 0 and Value of b is = 126.
2.Compile-time error occurs.
3.Prints Value of b = 126 and Value of b = 126.
4.Prints Value of b = 127 and Value of b = 126.
The answer is 1 can some one explain to me.
Peter Tran
Bartender

Joined: Jan 02, 2001
Posts: 783
Seema,
When you new an object of Processor(), you're calling the no argument c'tor for the class Processor(). The JRE inserts and hidden call to super() as the first line in the c'tor, so it looks like this (explicitly):

It does this, because the JRE wants to fully construct the base class before the derived class. In the base class c'tor for Process(), you invoke this.method(). The method you're invoking is for the derived class. You can never call a base method from an object of the derived class. That is there is no way ever to call DerivedClass.someBaseMethod(). Even if you cast the reference variable to the base class, you still wouldn't invoke the method in the the base class. In other words, this won't work either:

Okay, inside the methodA() of the Processor class, the variable byte b hasn't been initialized yet, because the object p of the derived class hasn't been fully constructed. Remember, we're still finishing constructing the base class. Just because the base class c'tor invokes a method in the derived class, doesn't mean the derived class is complete. Since the Processor object hasn't finished being built, the variable byte b gets the default value which is 0.
-Peter
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: overriding doubt
 
Similar Threads
why in x=x++ x keep not changed?
Jtips #39
another strange question
JTips MockExam No#39
what is it after all