• 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 ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

mock exam question need some help

 
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Author & Gold Digger
Posts: 7617
6
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic