• 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

polymorphic behaviour

 
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
public class Base
{
void first()
{
System.out.println("first() from base");
second();
}
void second()
{
System.out.println("second() from base");
}
}
class Derived extends Base
{
void second()
{
System.out.println("second() from derived");
}
public static void main(String args[])
{
Base b = new Derived();
b.first();
}
}
when I call first() in base second()in derived is call how come when it should call second() base. please explain.
 
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
When this code compiles and runs, the object reference b is constructed to have the Derived class's methods and members. Thus, when you call the first() method in this class you are calling the derived first() method from the class base, but it calls the newly overrided method from Derived.
Hope I helped you there,
Khalid
------------------
\\ //
~\// irucidal~
 
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,there:
My question, since you said object b will have it own member method and instance variable, I initialized two variables, one in base class the other in derived class, why b.i will give the value in Base class instead of Derived one?
Thanks
 
You guys wanna see my fabulous new place? Or do you wanna look at this tiny ad?
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic