File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

overriding doubt

seema ram

Joined: Feb 15, 2001
Posts: 3

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);
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

Joined: Jan 02, 2001
Posts: 783
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.
I agree. Here's the link:
subject: overriding doubt
It's not a secret anymore!