• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Polymorphisam

 
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 182
Eclipse IDE Chrome Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 145
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Marshal
Posts: 79177
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic