2015-04-16 45 views
0

能否請你解釋我這種奇怪的行爲?在初始化之前打印字段似乎在我初始化之後打印它

public class Car { 

    private int wheels; 

    public Car(int wheels) { 
     System.out.println("Before: " + wheels); // prints 3 before initialisation 
     this.wheels = wheels; 
     System.out.println("After: " + wheels); // prints 3 

    } 

    public static void main(String[] args) { 
     Car car = new Car(3); 
    } 
} 

如果你運行這段代碼,你將打印兩次3,而不是0,就在這時,場wheels3的初始化後。

回答

1

因爲當你是指wheels沒有this關鍵字,你指的是價值顯然是3

你行更改爲

System.out.println("Before: " + this.wheels); 

或更改參數名稱參數。

0

您正在引用局部變量而不是類變量。

使用this.wheels獲得初始化之前類變量(這將是0不是1)和輪轂的局部變量,它是3

0

名稱wheels引用了局部變量,而不是現場wheels。在這兩種情況下,局部變量的值都是3

如果您想引用對象的字段,請使用this.wheels

0

代碼不打印您認爲打印的變量。

public class Car { 

private int wheels;//<-- what you think it prints 

public Car(int wheels) {//<-- what it actually prints 
    System.out.println("Before: " + wheels); // prints 3 before initialisation 
    this.wheels = wheels; 
    System.out.println("After: " + wheels); // prints 3 

} 

public static void main(String[] args) { 
    Car car = new Car(3); 
} 
} 

如果要打印變量,請改爲使用this.wheels

相關問題