Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Help with this one from Markus Green's mock exam

 
Esenih Camai
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What will happen when you attempt to compile and run the following code?
class Base {
int i=99;
public void amethod(){
System.out.println("Base.amethod()");
}
Base(){
amethod();
}
}
public class RType extends Base{
int i=-1;
public static void main(String argv[]){
Base b = new RType();
System.out.println(b.i);
b.amethod();
}
public void amethod(){
System.out.println("RType.amethod()");
}
}
The answer is:
RType.amethod
99
RType.amethod
Why is not:
Base.amethod
99
RType.amethod
 
Maitham H
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
that is becuase the method amethod() in class Base, has been overriden by the method amethod() in class RType.
so when we reach the line
Base b = new RType();
the constructor of the super class Base is called first,inside it, a call to the method amethod() is made, remember that this method has been overriden by the subclass, so it will call the overriden version of it, which will be inside the class RType.
so we get "RType.amethod" written to the output.
instead of the "Base.amethod()".
hope this helps
 
Scott Kiel
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Esenih,
I had a similar question not long ago. As I understand this, variable references are determined at compile time by reference type and method references are determined at runtime by object type. In this case, when the base classes' constructor is called, the reference to amethod is determined to be RType because that is what type the object is.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic