• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

the most specific method is chosen rule (?)

 
kamilla miesak
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
I'm going over the mock exams on Dan Chisholm's web site. Below is the code for two different examples which are very similar and only one of them compiles. Part of Dan's explanation says that "The Java programming language uses the rule that the most specific method is chosen. The informal intuition is that one method declaration is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time type error". Can someone explain this a little further?
Thanks!
//this one prints "BB"
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) {
C c = new C();
m(c, c);
}
}
//compiler error
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");}
static void m(A x, C y) {System.out.print("AC");}
public static void main(String[] args) {
C c = new C();
m(c, c);
}
}
 
Jonathas Carrijo
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi kamilla,
I took some time thinking about it and, what came up is the following:
What you can't have is an ambiguity. Look at the command lines inside the main method:
C c = new C();
m(c, c);
I looked at the methods inside the C class and I found two candidates for m(c,c):
the 'm(A x, C y)' method and
the 'm(B x, B y)'.
Can you tell which of those is more specific??
Yeah, neither can I
But I really had never read about it... the book I'm studying by doesn't discuss this problem (Simon's Complete Guide), besides it is a very good one.
Thanx,
Jonathas
 
kamilla miesak
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks Jonathas
 
Jose Botella
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Exactly, Jonathas is right.
'm(A x, C y)'
'm(B x, B y)'.

While C is a widdening conversion to B, A to B isn't.
And the second method considered respect the first yields the same:
B is "more specific" than A, but B isn't to C.
Thus there is a draw, neither method is more specific than the other.
The JlS formally defines it in Choose the most specific method
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic