Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

overloaded methods

 
JayaSiji Gopal
Ranch Hand
Posts: 303
  • Mark post as helpful
  • send pies
  • 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.
 
Arnab karmakar
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • 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
 
Vipin Das
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • 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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic