Tae Hyung Kim
Tae Hyung Kim

Reputation: 190

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?

Upvotes: 1

Views: 721

Answers (3)

Anderson Vieira
Anderson Vieira

Reputation: 9049

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

Upvotes: 0

jwilner
jwilner

Reputation: 6606

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.

Upvotes: 0

Anubian Noob
Anubian Noob

Reputation: 13596

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.

Upvotes: 1

Related Questions