-1

Why is the C equal to 0. What should I do when I want calculate with the modified attributes. Why the C calculate with the default set up variables and not with the modified ones.


public class Object{

        int A;          
        int B;
        int C=A+B;
    
        int AddOnetoA(){
            A=A+1;
            return A;
        }

        int AddOnetoB(){
            B=B+1;
            return B;
        }
    
    
        void ShowA() {
            System.out.println(A);
        }
    
        void ShowB() {
            System.out.println(B);
        }
    
        void ShowC() {
            System.out.println(C);
        }
    }

And:


public static void main(String[] args) {
    Object obj =new Object();
    obj.AddOnetoA();
    obj.AddOnetoA();
    obj.AddOnetoA();
    obj.AddOnetoB();
    obj.AddOnetoB();
    obj.AddOnetoB();
    obj.ShowA();
    obj.ShowB();
    obj.ShowC();
}

output:

3

3

0

Community
  • 1
  • 1
  • 2
    Because when `C` is assigned both `A` and `B` are 0, when do *you* expect `C` to be computed? – luk2302 May 02 '19 at 12:11
  • I think this question is relted to [By Reference vs By Value](https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value?r=SearchResults&s=1|1976.6437) – Joakim Danielson May 02 '19 at 12:17

3 Answers3

1

C is computed only once. During the time of definition. The C=A+B gets executed during class loading time. You are updating A & B afterwards. So C stays as 0

In other words, the effect of your updates to a variable used in an expression are not retro-actively applied to those expressions.

rdas
  • 20,604
  • 6
  • 33
  • 46
0

The default values for integers which are not set is 0.

You do the following:

int A;          // sets A to 0
int B;          // sets B to 0
int C=A+B;      // sets C to A + B = 0 + 0 = 0

The notation C=A+B doesn't mean that the value C will be updated with each update of A or B but defines only its initial value.

You have to update its value with each increment of A or B variables by yourself:

int AddOnetoA(){
    A=A+1;
    c = A + B;      // here
    return A;
}

int AddOnetoB(){
    B=B+1;
    c = A + B;      // and here
    return B;
}

Don't create an object with the name Object which is the one that each one inherits from. Use for example MyObject for this simple case.

Lastly, I highly recommend you follow the Java conventions and start the name of variables and methods with a lower-case letter, such as:

int addOnetoB(){
    b = b + 1;      // equal to b++;
    c = a + b;      // and here
    return b;
}
Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
0

If you want C to reflect always the sum of A+B, you can remove int C; and alter showC:

void ShowC() {
    System.out.println(A+B);
}

This is a valid solutions if the effort to calculate C is low.

Conffusion
  • 4,335
  • 2
  • 16
  • 28