• 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Devaka Cooray
  • Knute Snortum
  • Paul Clapham
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Bear Bibeault
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Ron McLeod
  • Piet Souris
  • Frits Walraven
Bartenders:
  • Ganesh Patekar
  • Tim Holloway
  • salvin francis

overriding doubt  RSS feed

 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • 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
  • 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
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!