简体   繁体   中英

Java - Two methods with same name, same argument of different type, but the types are related hierarchically

Let's say I have

Interface A {
   public void doSomething(Object a);
}

Interface B {
   public void doSomething(Foo b);
}

and

Class C implements A, B {

   public void doSomething(Object a) {  print("a"); }
   public void doSomething(Foo b) { print("b"); }

}

I guess calling new C.doSomething(new Foo()); will print "b" , even though Foo extends Object.

but what about if I want a common behavior from sub-methods :

Class C implements A, B {

   public void doSomething(Object a) {  print("common behavior from " + a ); }
   public void doSomething(Foo b) { doSomething((Object) b); }
   public void doSomething(Bar c) { doSomething((Object) c);}

}

Will that work when I call doSomething with Foo and Bar or will they end up in an infinite loop because at the end doing ((Object) c) instanceof Bar == true ?

How does Java defines which method to call?

Overload resolution happens at compile time. It doesn't matter what the runtime type of b or c is. As long as they're cast as Object , it'll call the Object overload. So your example should work fine.

Another common use case is where you want to pass a literal null to a method and you need to cast it to some type to avoid overload ambiguity. Eg c.doSomething((Foo)null) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM