Is there a way to pass variables from different methods into a single method?

In the below code snippet, I have 4 methods A, B, C, D in class test. Each method contains a number of variables. I would like to pass some of the variables from methods A, B, and C into method D. In other words:

public class test {
    public void A() {
         int a;
     }

    public void B() {
         int b;
     }

    public void C() {
         int c;
     }

    public void D(a, b, c) {
         int d = a + b + c;
     }
}

2 answers

  • answered 2018-05-16 05:25 Thihara

    No.

    You have declared he variables a, b, c inside the methods, consequently these variables are therefor method scoped. That is they can only accessed within that scope.

    If you want to retain the variable state outside of the method you need to make these variables object scoped variables.

    public class test {
        int a, b, c;
        public void A() {
             this.a=1;
         }
    
        public void B() {
             this.b=2;
         }
    
        public void C() {
             this.c=3;
         }
    
        public void D() {
             int d = this.a + this.b + this.c;
         }
    }
    

  • answered 2018-05-16 05:28 user7294900

    Adding to @Thihara you can also return the variable in each method and call method in D()

    public class test {
    public int  A() {
         int a;
         return a;
     }
    
    public int  B() {
         int b;
         return b;
     }
    
    public int C() {
         int c;
         return c;
     }
    
    public void D() {
         int d = A() + B() + C();
     }
    }