• 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 ...
  • Tim Cooke
  • Campbell Ritchie
  • Ron McLeod
  • Junilu Lacar
  • Liutauras Vilda
  • Paul Clapham
  • Jeanne Boyarsky
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Piet Souris
  • Carey Brown
  • Jesse Duncan
  • Frits Walraven
  • Mikalai Zaikin

overriding doubt

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() {

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.
Posts: 783
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
pie. tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
    Bookmark Topic Watch Topic
  • New Topic