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: 1815
posted
0
...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
posted
0
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
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.