• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt on program output from overriding

 
R .sourav nayak
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Could some one tell me why the out put is 5, sub instead of 2 ,sub from the following program:

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();
}
}
thanks in advance
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If there is an instance variable in the subclass with the same name as an instance variable in the superclass, then the reference type determines which variable is used not the runtime type of the object.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic