如何更改实例化 class 变量

how do I change instanced class variables

我的代码简化后类似于:

//class 1
public class Main
{
   public static void main(String[] args)
   {
      Process process = new Process(0); //creates new process with ID of 0 
      process.id = 1; //error - I can't call and change process.id here
      System.out.println(process.id);

   } 
}

//class 2:
public class Process()
{
   //constructor
   public Process(int tempID)
   {
    int id = tempID;
   }
}

我遇到评论错误的地方是我坚持的地方。我想访问和更改我拥有的此实例 class 的 id 变量,但我不确定如何

将 id 定义为实例变量。

由于 id 是在本地方法内部定义的,因此您可以使用 p.id 访问它。 因此,将 id 创建为实例变量,并创建一个 setter 方法来更新其值。所以你的 class 看起来像这样。

public class Process(){

  public int id;   //<- Instance Varaible

 //constructor
 public Process(int tempID){
    int id = tempID;
 }
 
 //Setter method
 public void setId(int id){
     int id = tempID;**strong text**
 }

}

现在您可以像这样更改值

 Process p = new Process(0);
 p.setId(1);          // Change Value
 System.out.println(p.id);