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

mock exam question need some help

 
aryan sanghvi
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class Super
{ int index = 5;
public void printVal()
{ System.out.println( "Super" );
}
}
class Sub extends Super
{ int index = 2;
public void printVal()
{ System.out.println( "Sub" );
}
}
public class Runner
{ public static void main( String argv[] )
{ Super sup = new Sub();
System.out.print( sup.index + "," );
sup.printVal();
}
}
The above question is from:
MindQ_s_Sun_Certified_Java_Programmer_Practice_Test.htm
ans: (5, super)
It is unclear to me that that method from subclass
is executed.But the value is sup.index as expected.
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm sorry but if you try to run the code the output is not (5,super) but (5,sub)...
The statement Super sup = new Sub();
declares a reference variable of type Super referencing an object of runtime type Sub. Field accesses are resolved according to the declared type of the variable (i.e. Super) while methods are resolved according to the runtime type of the variable (i.e. Sub). Thus,
sup.index is resolved to the value of the member called index in the class Super.
Since method printVal() is overridden in Sub, sup.printVal() is resolved to the printVal() method in the class Sub.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic