Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

behaviour of superclass method!!!

 
sivaramp pratapa
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i have three classes altogether
the heirarchy goes this way
class A
{
void M1()
{
Print("I am in M1 of class A");
M2();
}
void M2()
{
Print("I am in M2 of class A");
}
};
class B extends A
{
void M2()
{
Print("I am in M2 of class B");
}
};
class C
{
public static void main(String args[])
{
B b =new B();
b.M1();
}
};
The output of this is
Print("I am in M1 of class A");
Print("I am in M2 of class B");
when i call M2() from M1() of A, why is that M2() of B is responded.
please explain.
 
Joel McNary
Bartender
Posts: 1840
Eclipse IDE Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
...Because the object that is responding to the method is of class B. This feature is called polymorphism and is a very important part of object-oriented programming. See How my Dog learned Polymorphism
 
Joe Pluta
Ranch Hand
Posts: 1376
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's important to realize that you created an object of class B. By default, it inherits all the methods of class A (except private methods).
So, by default B starts witj two methods, M1 and M2. B inherits the M1 method from class A, so it uses the code in class A. However, B declares it's own version of M2, which in effect overrides the M2 method in class A. So it looks a little like this:
A B
M1 --
M2 M2
The dashed lines indicate that B has no M1 method of its own, so it must use the one from class A. A uses its own M1 and M2, but B uses the M1 from A and its own M2.
Ta da! You have now mastered inheritance and polymorphism!
Joe
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic