• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Calling Overridden methods and overshadowed variables

 
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Why is there difference between calling the overidden methods and overshadowed variables based on the object type(class) and reference (as stated in the book of Khalid )
 
Ranch Hand
Posts: 158
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi
I am not sure what you mean.But if you mean something that involves the code:
<code>
class Base{
String str="in Base";
void amethod()
{ system.out.println("in Base");

}
}
clas Sub extends base{
String str="in Sub";
void amethod()
{
System.out.println("In Sub");
}
}
class test{
public static void main(String args[])
{
Base b;
Sub s=new Sub();
b=s;
s.amethod();
System.out.println(s.str);
b.amethod();
System.out.println(b.str);
}

}
}
</code>
the output is: in Sub //amethod of Sub invoked by s
in Sub //varaible str of Sub accessed by s
in Sub //amethod of Sub invoked by b
in Base //varaible str of Base accessed by b
So the method called depends on the object, not on the object reference . Here the object reference of type Base points to an object of type Sub. So method amethod of class Sub is invoked.But variables accessed depends on the object reference.Since the object reference is of type Base, the variable 'str' of the Base class is accessed.
I hope this is what you wanted to know
regards
Tanveer
 
Stephen Joseph
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you Tanveer.You guessed my Q right, but if you can tell me what is the reason for this difference why cant overridden methods and overshadowed variables be called in the same way.
 
Sheriff
Posts: 5782
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Since this topic is not concerned with Threads and Synchronization, I am moving it to a more appropriate forum - Java in General(intermediate). Please continue the discussion there.
Thanks!
Ajith
 
reply
    Bookmark Topic Watch Topic
  • New Topic