Click to See Complete Forum and Search --> : Classes


Deepa Natarajan
August 16th, 1999, 11:33 AM
Hi,

I need an urgent explanation for the following code.

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();
}
}
Ans: 5,sub

Thanks,
Deepa

varbsjava
August 17th, 1999, 02:15 AM
Hi,

Variables in java are statically linked to the object and accessed depending upon the type
of the object.But the methods are accessed by the reference of the object.
So when u say sup.printVal(), the printVal() method of Sub class is called
because the object sup of type Super carries the reference of its sub class Sub.
As instance methods are accessed by reference, the method printVal() of Sub class.
So u r getting the output as "Sub".

When u are trying to print the value of index using sub.index, the object type is checked
and the index value of that object type is output. So only u get "5". If u want to
get%