• 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

overriding question

 
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 doSomething ( A x , A y ) {System.out.print("AA");}
static void doSomething ( A x , B y ) {System.out.print("AB");}
static void doSomething ( B x , A y ) {System.out.print("BA");}
static void doSomething ( B x , B y ) {System.out.print("BB");}
static void doSomething ( C x , C y ) { System.out.println("CC");}

public static void main(String[] args) {
doSomething(null,null);
}
}


it prints cc , can anyone tell me how this happens.
thanks
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This is a case of the "most specific" method being selected.

A null reference can represent any object type, so it can match any non-primitive argument type.

In this case, the choices are A, B, and C (in various combinations). A null reference could represent any of these. But C is "more specific" than B because a C reference can be upcast to type B, but not vice versa. Likewise, B is more specific than A. So the most specific choice here is the method that takes two C references.

For other examples, search this forum for "most specific."

(For the dirty details, see JLS - 15.12.2.5 Choosing the Most Specific Method.)
 
marc weber
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
PS: These methods are overloaded -- not overridden.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic