Search code examples
javapolymorphism

Java Passing objects to a method


Suppose that X and Y are classes such that Y extends X. Also, let method(X xObj) be a method of X. Why does the following code compile?

X xObj = new X();
Y yObj = new Y();
xObj.method(yObj);

Also, are there other similar cases in which code that seems incorrect compiles?


Solution

  • If Y extends X, then, Y is an X. You can substitute X for Y (consistantly) in any application.

    You can do all this fancy stuff:

    X object = new Y();
    object.method(object)
    Y objY = new Y();
    object.method(objY);
    objY.method(object);
    

    The main thing to note is that a child class is the type of it's parent.