File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Java » Java in General
Bookmark "behaviour of superclass method!!!" Watch "behaviour of superclass method!!!" New topic

behaviour of superclass method!!!

sivaramp pratapa

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");
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();
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

Joined: Aug 20, 2001
Posts: 1824

...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:
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!
I agree. Here's the link:
subject: behaviour of superclass method!!!
It's not a secret anymore!