Search code examples
javainstance-variables

how do I change instanced class variables


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


Solution

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