This week's giveaway is in the EJB and other Java EE Technologies forum.
We're giving away four copies of EJB 3 in Action and have Debu Panda, Reza Rahman, Ryan Cuprak, and Michael Remijan on-line!
See this thread for details.
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


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
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: 92
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: 36453
    
  15
"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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Polymorphisam
 
Similar Threads
Qn from dan exam
inheritance question
Could any one of you explain me this code
question
Overload method