1
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.

3
  • You could simplify the example by using static methods. Commented Mar 22, 2011 at 12:33
  • Make A extend Z and see which one is called. ;) Commented Mar 22, 2011 at 12:33
  • ya...i extended Z, its giving A reference and other reference. Commented Mar 22, 2011 at 12:49

3 Answers 3

5

Every class is a subclass of java.lang.Object even if you don't extend it explicitly.

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

1 Comment

Succinct, and entirely answers the question.
2

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.

3 Comments

Ya 'S' class is existing else it is giving a compilation error.
Since i am passing 'S' class object and nothing is defined in 'S' class like no variables and methods. Then the address to which the reference of the 'S' class pointing is passed or null will be passed in fun() method argument?
@Nitish S will be passed (a handle to S, that is). but not that java is pass-by-value, so you can't reassign the reference
0

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.

Comments

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.