• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

question from Marcus Green's website tutorial

 
Ray Chang
Greenhorn
Posts: 25
  • 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()");
}
}
1)
RType.amethod
-1
RType.amethod
2)
RType.amethod
99
RType.amethod
3)
99
RType.amethod
4)
Compile time error
why the answer is B.
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13058
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because the addresses of variables are decided at compile time but methods are looked up dynamically.
So - the line:
System.out.println( b.i )
uses the address of i in the Base class. As far as the compiler is concerned, b is a Base reference.
Bill
 
Ray Chang
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much? But why the answer isn't c?
 
Bishal P
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think this question was answered before... and i guess the reason why the answer is B is becoz the methods are polymorphed but the instance variables are not..
 
Barkat Mardhani
Ranch Hand
Posts: 787
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much? But why the answer isn't c?

The subclass has no constructor. So an implicit contructor Rtype() will be invoked. That will first invoke super class constructor Base(). Base() class constructor is calling amethd(). Now because of polymophism amethod() of Rtype will be invoked because after all the object's actual type is Rtype(). That amethod will print the first line.. and I guess you know the rest of story...
 
Sabarish Sasidharan
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also note that, if the amethod() had private accessibility the amethod() invoked from the constructor of the Base class would be different... That is because private members cannot be overridden. This is shown in the code below which is the original code, modified a bit.
 
Barkat Mardhani
Ranch Hand
Posts: 787
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That is correct Sabarish. Good point...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic