• 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: 39
  • 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 {
static void m(A x, A y) {System.out.print("AA");}
static void m(A x, B y) {System.out.print("AB");}
static void m(B x, A y) {System.out.print("BA");}
static void m(B x, B y) {System.out.print("BB");}
public static void main(String[] args) {
A a1; B b1;
m(null,null); m(a1=null,b1=null); m(b1, a1);
}}

In the above program why the output is BBABBA, why not AAABBA

please explain

Thank You Sampath
 
Ranch Hand
Posts: 335
  • 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 {
static void m(A x, A y) {System.out.print("AA");}
static void m(A x, B y) {System.out.print("AB");}
static void m(B x, A y) {System.out.print("BA");}
static void m(B x, B y) {System.out.print("BB");}
public static void main(String[] args) {
A a1; B b1;
m(null,null); m(a1=null,b1=null); m(b1, a1);
}}

I am not 100% sure but as per my evaluation
null can be passed to any reference

so m(null,null) method called is most specific as per hierarchy
next you pass a1,b1 so AB than b1,a1 so BA.
 
Ranch Hand
Posts: 220
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Santana Iyer:
so m(null,null) method called is most specific as per hierarchy
next you pass a1,b1 so AB than b1,a1 so BA.



Yes I think thats right, the most specific choice is chosen. However, this is because B is a subclass of A
Suppose you have another class C not related to B, and methods
m(B b1, B b2);
and
m(C c1, C c2);
and call
m(null, null),
the compiler will NOT be able to resolve it and will throw and ambiguous call error.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic