wood burning stoves 2.0*
The moose likes Java in General and the fly likes behaviour of superclass method!!! Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "behaviour of superclass method!!!" Watch "behaviour of superclass method!!!" New topic
Author

behaviour of superclass method!!!

sivaramp pratapa
Greenhorn

Joined: Jul 05, 2003
Posts: 11
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

Joined: Aug 20, 2001
Posts: 1817

...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


Piscis Babelis est parvus, flavus, et hiridicus, et est probabiliter insolitissima raritas in toto mundo.
Joe Pluta
Ranch Hand

Joined: Jun 23, 2003
Posts: 1376
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
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: behaviour of superclass method!!!