2

I have a class B that contains these four methods:

public class B {

public void f(int x) {
    System.out.println("1");
}

public void f(Object x) {
    System.out.println("2");
}

public void f(List x) {
    System.out.println("3");
}
public void f(Collection x){
    System.out.println("4");
}

and in the main I have these commands:

B o = new B();
    Integer n = new Integer(3);
    List<Integer> l = new ArrayList<>();
    Collection<Integer> m = new ArrayList<>();
    o.f(3);
    o.f(n);
    o.f(l);
    o.f(m);

The result will be:
1
2
3
4

why does "3" considered as int while Integer(3) concidered as Object? And why List or Collection isn't considered as Object?

Steve Kuo
  • 61,876
  • 75
  • 195
  • 257

2 Answers2

5

It's picking the most specific version of the method at compile time.

Integer is being considered an Object because it is an Object (it inherits from Object):

https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html

Collection and List would be considered an Object as well if you didn't have the more specific versions of the methods.

But since you also overloaded the method for Collection and List, those are used.

eugenioy
  • 11,825
  • 28
  • 35
0

You have two issues here, Ill just look at the List, Collection, Object since the Integer int is answered elsewhere.

The most specified method is used.

So a List inherits from Collection and they are both Object. That makes List more specific so when you pass the List, it chooses the method that takes List as an argument. Even though the List could be passed to the Object or Collection method. You can achieve the same effect with a cast.

o.f(((Object)l));

Will result in a 2.

matt
  • 10,892
  • 3
  • 22
  • 34