A1 a = new A1(); A1 b = new B1(); A1 c = new C1(); C1 cc = new C1();
a.m1(cc); b.m1(cc); c.m1(cc);
a.m2(); b.m2(); c.m2(); } }
Joined: Mar 13, 2004
Polymorphisn depends on the actual type of the object the instance method is called on. However, the matching of method signatures to argument types is done at compile time based on the declared type of the reference.
In this case, the arguments used to call method m1() are all of type A1.
Method B1.m1(B1) cannot take an A1 argument because an A1 object might or might not actually be a B1 object. The same thing applies to method C1.m1(C1). So the only m1() method that can accept an A1 argument is A1.m1(A1).
Since only one of the overloaded m1() methods has a matching signature, polymorphism never happens.
SCJP 1.4, SCWCD in process
Joined: Feb 17, 2005
Let us try to think in the compiler way
//1 Do I have a matching function in class A1 for this? Yes. void m1(A1 a) can accept object cc. (Since cc is an instance of class (c1) derived from A1 --> Displays A1
//2 Do I have a matching function in class B1 to accept object cc? Well. Though I don't have on my own, I inherited one function from A1 void m1(A1 a) which can take this argument cc.
//3 Above mentioned holds good here as appropriate to class C1
The point to note here is that compiler always looks for appropriate methods in the type of object it refers to and not the parent class A1..
//4 I have an appropriate function in class A1 to execute this statement. //5 Above mentioned holds good for class B1
A1 A1 A1 A1** B1** C1** Correct me if I am assuming something wrong...