[英]What happens when a subclass object is passed to a method with a superclass parameter?
[英]What happens when a parameter is passed with the -- operator?
我在 Java 中遇到了以下代碼:
public static void foo (int a, int b) {
System.out.println("a: " + a);
System.out.println("b: " + b);
}
public static void main(String[] args) {
int c = 1;
foo(c--, c);
System.out.println("c: " + c);
//The output is:
//a: 1
//b: 0
//c: 0
有人可以解釋一下,這是為什么? 我會c--
猜測,只有第一個打印語句會受到c--
影響。 但是如果它確實永久改變了 c 的值,為什么第一行仍然打印 1?
您可以使用++c
或c++
遞增,類似地,您可以使用--c
或c--
遞減
對於++c
和--c
,您實際上是在告訴 Java“更改值,然后使用新值執行某些操作”
對於c++
和c--
,您是在告訴 java“加載值,然后更改它”。
現在,這就解釋了為什么 A 是 1,C 是 0。但是為什么 B 也是 0?
當您調用函數時,參數會按順序解析。 通常這僅在您將方法的直接結果作為參數傳遞時才相關。
例如,調用methodX( methodY(), methodZ())
,其中方法簽名為void methodX(int a, int b);
int methodY();
和int methodZ();
,然后方法 Y 將在 Z 之前執行,Z 在 X 之前執行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.