• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

Casting

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi!!
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 + "," );

S1.printVal();
}
}
 
Ranch Hand
Posts: 1492
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
Manfred.
 
Live ordinary life in an extraordinary way. Details embedded in this tiny ad:
Clean our rivers and oceans from home
https://www.kickstarter.com/projects/paulwheaton/willow-feeders
reply
    Bookmark Topic Watch Topic
  • New Topic