Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/358.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何更改实例类变量_Java_Instance Variables - Fatal编程技术网

Java 如何更改实例类变量

Java 如何更改实例类变量,java,instance-variables,Java,Instance 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.

我的简化代码如下所示:

//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;
   }
}
我有评论错误的地方就是我一直在坚持的地方。我想访问并更改我拥有的这个实例类的id变量,但我不确定如何将id定义为实例变量。 由于id是在方法内部本地定义的,因此可以使用
p.id
访问它。 所以创建id作为一个实例变量,比如,为了更新它的值,创建一个setter方法。所以你的班级看起来是这样的

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);