aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Instance Variables Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Instance Variables" Watch "Instance Variables" New topic
Author

Instance Variables

Rekha Sivadasan
Greenhorn

Joined: Feb 15, 2001
Posts: 14
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

Joined: Feb 25, 2001
Posts: 82
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


Hima<BR>Sun Certified Java Programmer
Jane Griscti
Ranch Hand

Joined: Aug 30, 2000
Posts: 3141
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


Jane Griscti
SCJP, Co-author Mike Meyers' Java 2 Certification Passport
Rekha Sivadasan
Greenhorn

Joined: Feb 15, 2001
Posts: 14
Thanks Hima and Jane.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Instance Variables
 
Similar Threads
Objects and there references
need help
Question
Use of constructor in abstract class?
mock exam question need some help