簡體   English   中英

JAVA 實例與局部變量

[英]JAVA instance vs local variable

import comp102x.IO;  
  
public class testing {
  
        private int x;

        public testing(int x) {
  
                x = x;
        }

        public static void main(String[] args) {
  
                testing q1 = new testing(10);
                IO.outputln(q1.x);
        }
}

為什么 output 是 0 而不是 10? 這是一個 JAVA 腳本。 實例和局部變量的概念讓我很困惑,有人可以幫忙解釋一下嗎?

public testing(int x) {      
  x = x;
}

在這里,您只需將局部變量 x 的值重新分配給自身,它不會更改實例變量。

更改局部變量的名稱,如下所示:

public testing(int input) {
  x = input;
}

或確保將值分配給實例變量,如下所示:

public testing(int x) {
  this.x = x;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM