File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Casting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Casting" Watch "Casting" New topic


Kiran Malagi

Joined: Jan 05, 2001
Posts: 2
Can someone explain the following piece of code?
class Super
{ int index = 3;
public void printVal()
System.out.println( "Super"+index );
class Sub extends Super
{ int index = 2;
public void printVal()
{ System.out.println( "Sub"+index );
public class Runner
{ public static void main( String argv[] )
{ Sub sub = new Sub();
Super sup = new Super();
Super S1 = (Sub)sub;
System.out.print( S1.index + "," );

Manfred Leonhardt
Ranch Hand

Joined: Jan 09, 2001
Posts: 1492
The example shows that in Java methods can be overridden but member variables can not. It also shows a great case for not allowing direct access to internal variables. If we take your example and create accessors in each class (overridding in Sub) we would get the result: "2,Sub2" instead of the current result: "3,Sub2"!
For the case of S1 member variable index. Java knows that the type is Super from the declaration. Therefore you get the value of index = 3 because that is what super initializes its member variable to.
In the case of S1 method call, Java knows that the S1 is actually a reference to an object of class Sub, therefore it starts at the Sub class and tries to find a matching method. It finds it there so we get the result from Sub class for printVal.
I agree. Here's the link:
subject: Casting
jQuery in Action, 3rd edition