What is the mechanism behind object class in java?
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("o开发者_StackOverflow社区ther 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 is a subclass of java.lang.Object even if you don't extend it explicitly.
Every class has java.lang.Object
as a parent - even if you don't write extends Object
, the compiler adds it automatically. To quote the javadoc:
Class Object is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class.
S
obviously exists, otherwise it wouldn't compile. Then the compiler chooses the most specific method to invoke. S
does not match the signatures with neither Z
nor A
, and it matches the Object
one.
S is a type of Object, as every class in Java is a subclass of Object. When Java search for a suitable method overload for fun(), fun(Object object) matches the argument and hence it is invoked.
Try to take a look at Method Overloading in Java.
精彩评论