英文:
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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论