0

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?

1
  • You should try it and find out. Java defines the behavior in it's specifications. Commented Sep 26, 2016 at 23:25

1 Answer 1

2

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. E.g. c.doSomething((Foo)null).

Sign up to request clarification or add additional context in comments.

1 Comment

Using the null parameter is a good example explanation. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.