• 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

overriding doubt

 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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.
 
Bartender
Posts: 783
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic