简体   繁体   English

Java 将对象传递给方法

[英]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 和 Y 是 Y 扩展 X 的类。另外,让 method(X xObj) 是 X 的一个方法。为什么下面的代码编译?

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 .如果Y扩展X ,则YX You can substitute X for Y (consistantly) in any application.您可以在任何应用程序中(始终)用X替换Y

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.如果method()的参数是X类型,则任何属于X子类型的对象(在示例中为Y )也可作为参数有效。

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类为例。 Integer extends Number , and Number implicitly extends Object . Integer扩展Number ,而Number隐式扩展Object Any object of type Integer is also a Number and also an Object .任何Integer类型的对象也是一个Number和一个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.这意味着匹配 X 的方法将匹配其子类 Y。这是因为,对于编译器来说,Y 保证像 X 一样运行,因为这是 OOP 的基本约定之一。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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