|
Re: Need help regarding this code snippet
|
Posted: Feb 15, 2005 6:33 PM
|
|
Hidden fields and methods are resolved at compile time using the TYPE of the reference variable. So, s.index will point to index member variable of the TYPE of s. See the modifed Runner class's output. We have only one object of Sub class. We can refer to Super's index or Sub's index depedning on the variable sup, sup1 and (Sub)sup TYPE. In first case, TYPE is Super, so you get 5. In second and third, TYPE is sub, so you get 2.
public class Runner {
public static void main( String argv[] ) {
Super sup = new Sub();
Sub sup1 = (Sub) sup;
System.out.print( sup.index + "," );
System.out.print( sup1.index + "," );
System.out.print( ((Sub)sup).index + "," );
sup.printVal();
}
}
|
|