aspose file tools*
The moose likes Java in General and the fly likes Polymorphisam Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Polymorphisam" Watch "Polymorphisam" New topic
Author

Polymorphisam

Aruna Balasuriya
Ranch Hand

Joined: Nov 14, 2009
Posts: 44


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

Joined: Jun 02, 2009
Posts: 182

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


A.A.Anbarasu
Sriram Sharma
Ranch Hand

Joined: Apr 12, 2006
Posts: 98
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

Joined: Oct 13, 2005
Posts: 39865
    
  28
"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.
 
 
subject: Polymorphisam