• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Instance Variables

 
Rekha Sivadasan
Greenhorn
Posts: 14
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the programme below, please exaplain why the value of sup.index is 5 instead of 2.
class Super{
public int index = 5;

Super(){
System.out.println("The value of index " + index + " In Super Class");
}
public void printVal(){
System.out.println( "Super" );
System.out.println("value of index in super " + index);
}
}
class Sub extends Super
{
public int index = 2;

Sub(){
System.out.println("The value of index " + index + " In Sub Class");
}
public void printVal(){
System.out.println( "Sub" );
System.out.println("value of index in sub " + index);
}
}
public class Runner{
public static void main( String argv[] ){
Super sup = new Sub();
System.out.print( sup.index + "," );
sup.printVal();
}
}
Thanks
Rekha
 
Hima Mangal
Ranch Hand
Posts: 82
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi rekha..
well the code prints 2(the subclass' objects value) and not 5(the superclass' objects value).. because member variables are bound at acompile time, and not run time..so they are looked up based on the type of reference to them at compile time, which was a super class' reference..
hope this helps..
------------------
Hima
 
Jane Griscti
Ranch Hand
Posts: 3141
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Rekha,
Dynamic Binding rules do not apply to instance variables. When you access an instance variable directly (ie not through a method); the declared type is used.
The declared type of the object sup is Super so when the reference <code>sup.index</code> is resolved Java checks the Super class for the instance variable 'index' and returns it's value, 5.
When you invoke the method <code>sup.printVal()</code> Java checks the Runtime type of the object, which is Sub. It invokes the <code>printVal()</code> method in the Sub class. The <code>printVal()</code> references the variable 'index'. Java checks to see if there is a variable 'index' in the same class. There is so it uses it's value '2'.
Hope that helps.
------------------
Jane Griscti
Sun Certified Programmer for the Java� 2 Platform
 
Rekha Sivadasan
Greenhorn
Posts: 14
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Hima and Jane.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic