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

Polymorphisam

 
Aruna Balasuriya
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


This prints AAA ??? How it Happen It should print ABC as c2 reffering to C type object. Please give me a detailed explanation.
 
Anbarasu Aladiyan
Ranch Hand
Posts: 182
Chrome Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

At line 28 ==> A c2 = new C();

it means you are creating Polymorphic reference. that is super class reference variable(class A) is refers to sub class object(Class C).

Since we extend super classes A and B in C,we have three overloaded methods in class C. so when we invoke using c2 reference variable , it will look for methods that are available in both the classes (A and C). In this case only one method is matched (super class A's method , which can accept all the sub types).

So that it prints AAA.

Make some changes At line 28 ==> C c2 = new C();
then it will print ABC

Regards,
Anbarsu
 
Sriram Sharma
Ranch Hand
Posts: 130
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Aruna,

Always remember the following in Java

For overloading, method in reference is used.
For overriding, method in the object is used.

The parent class "A" can accomodate all three class types "A", "B" and "C". Because it is the parent.
So, when you say
A c2 = new C(); c2.m1(a1);
JVM will look for the method "m1" in class A

Suppose, you give...
B c2 = new C(); in your code
your output will be "ABB"

And for the code
C c2 = new C(); in your code
your output will be "ABC"

Any more queries???

Regards,
Sriram
 
Campbell Ritchie
Sheriff
Posts: 48921
58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"Method in reference" is also called the declared type of an object and "method in the object" is also called the runtime type.

Remember that instance methods (including those inherited from interfaces) are overridden and nothing else is overridden. Static methods and fields are not overridden.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic