• 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:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

overloaded methods

 
Ranch Hand
Posts: 303
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
class A {}
class B extends A {}
class C extends B {}
class D {
void m1(A a) {System.out.print("A");}
void m1(B b) {System.out.print("B");}
void m1(C c) {System.out.print("C");}
public static void main(String[] args) {
A c1 = new C(); B c2 = new C();
C c3 = new C(); D d1 = new D();
d1.m1(c1); d1.m1(c2); d1.m1(c3);
}}

What is the result of attempting to compile and run the program?

a. Prints: AAA
b. Prints: ABC
c. Prints: CCC
d. Compile-time error
e. Run-time error
f. None of the above

in this eg, we have three overloaded methods in class D.
My q: in case of overloaded methods, in same class or in subclasses, the method call invocation is based on the variable reference type and not the run time reference type of the object instance.

please correct me.
 
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi jayashree,

Please put ur question clearly.
Let me explain what I have understood from ur question.

The a supper class object can be used to reference a sub class object, but the reverse way is not possible. But that does not mean that if u refer a super class object to a subclass object then it would call the functios of superclass. Thats why there is nothing complicated here. The subclass methods are called cooly.

Arnab
 
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
You are right.
FYI: If there are overloaded methods with base class , subclass parameters. Always the method which contains more specific subclass will be called.


In the above example there is no method for the type E, so call d1.m1(e) will execute void m1(C c) {System.out.print("C");} rather than calling the other methods. If the method void m1(C c) {System.out.print("C");} is not present it will execute void m1(B b) {System.out.print("B");}
and so on.
 
reply
    Bookmark Topic Watch Topic
  • New Topic