class A{}
class Z{}
class S{}
public class Demo6 {
void fun(A a){
System.out.println("A reference");
}
void fun(Z z){
System.out.println("Z reference");
}
void fun(Object o){
System.out.println("other reference");
}
public static void main(String args[]){
new Demo6().fun(new A());
new Demo6().fun(new S());
}
}
Output of the above code is coming:
A reference
other reference
My confusion is how “other reference” is printing when we are passing ‘S’ class object. Elaborate the actual mechanism of how ‘S’ class object is compatible with the “Object” class.
Every class has
java.lang.Objectas a parent – even if you don’t writeextends Object, the compiler adds it automatically. To quote the javadoc:Sobviously exists, otherwise it wouldn’t compile. Then the compiler chooses the most specific method to invoke.Sdoes not match the signatures with neitherZnorA, and it matches theObjectone.