简体   繁体   中英

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?

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 .

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM