如何更改实例化的类变量

huangapple go评论63阅读模式
英文:

how do I change instanced class variables

问题

//class 1
public class Main
{
    public static void main(String[] args)
    {
        Process process = new Process(0); //创建一个具有ID 0的新进程
        process.id = 1; //错误 - 我不能在这里调用并更改process.id
        System.out.println(process.id);

    }
}

//class 2:
public class Process()
{
    //构造函数
    public Process(int tempID)
    {
        int id = tempID;
    }
}
英文:

my code simplified looks something like:

//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;
   }
}

Where I have the comment error is what I'm stuck with. I want to access and change the id variable of this instanced class I have, but I'm not sure how to

答案1

得分: 1

# 将 id 定义为实例变量
由于 id 是在方法内部局部定义的所以您可以使用 `p.id` 来访问它
因此将 id 定义为实例变量并为更新其值创建一个 setter 方法因此您的类将如下所示

    public class Process() {
    
      public int id;   //<- 实例变量
    
      // 构造函数
      public Process(int tempID) {
          id = tempID;
      }
     
      // Setter 方法
      public void setId(int tempID) {
          id = tempID;
      }
    
    }

现在您可以像这样更改值

     Process p = new Process(0);
     p.setId(1);          // 更改值
     System.out.println(p.id);
英文:

Defined id as an instance variable.

Since id is defined inside the method locally that is why you can access it using p.id.
So create id as an instance variable like and for updating its value create a setter method. So your class would look like this.

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**
 }

}

Now you can change the value like this

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

huangapple
  • 本文由 发表于 2020年9月25日 11:20:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/64057326.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定