1

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?

3 Answers 3

1

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.

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

Comments

0

The type of a method parameter always matches its subtypes. That means a method which matches X will match its subclass Y. This is because, to the compiler, a Y is guaranteed to act like an X, as that's one of the fundamental contracts of OOP.

Comments

0

If the parameter for method() is of type X, any object that is a subtype of X (Y, in the example) is also valid as argument.

Note that you can also do:

X yObj = new Y(); // declare variable yObj with type X and reference Y instance
xObj.method(yObj);

Take, for example, the Integer class. Integer extends Number, and Number implicitly extends Object. Any object of type Integer is also a Number and also an Object. So you could do:

static void print(Object obj) {
    System.out.println(obj);
}

And call:

Integer n = 5;
print(n);

Output:

5

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.