• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Method invocations

 
Mathangi Shankar
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please read code1,2,3 below:-

Code 1:

class GFC218 {
static void m(Object x) {System.out.print("Object");}
static void m(String x) {System.out.print("String");}
public static void main(String[] args) {m(null);}
}

Output:String

Code2:

class GFC200 {}
class GFC201 {
static void m(Object x) {System.out.print("Object");}
static void m(String x) {System.out.print("String");}
static void m(GFC200 x) {System.out.print("GFC200");}
public static void main(String[] args) {m(null);}
}

***Compile time error

Code 3:
class GFC202 {} class GFC203 extends GFC202 {}
class GFC204 {
static void m(GFC202 x) {System.out.print("GFC202");}
static void m(GFC203 x) {System.out.print("GFC203");}
public static void main(String[] args) {m(null);}
}

Output: GFC203


I did not understand the o/p of 2 and 3.
In the code2 both the String as well as GFC200 classes extend Object class implicitly then where is the ambuiguity and hence why does it give compile time error.

In the code 3 how does GFC203 get printed or how is it more specific then GFC202 class.

If anybody could explain it would be appreciated.

Thanks,

Mathangi.
 
Joe Borderi
Ranch Hand
Posts: 151
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The rules are that the compiler will resolve overloaded method calls to the most derived class and ambiguity causes compiler errors.
 
Jay Pawar
Ranch Hand
Posts: 411
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mathangi,
To get good grasp of this concept. I would suggest you go through the excellent article written by Corey . Here is the link

Hope that helps ya.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic