-1

Let say I have a typical java class like

public class Waiter {
    private int Id;
    private String name;
    private int active;
    //Including constructor, getter and setter
}

And now I want to make a function that can change the variable in active. I know, in this case, I can simply use the setters, but I want to inside a function that I can call when I need to.

My function currently looks like this

public void login(int a) {
    int b = 2;
    a = b + a;
}

Now I want to call it with

login(2)

but it won't update my a value in main?

takendarkk
  • 3,347
  • 8
  • 25
  • 37
  • 1
    You want to make change in the value held by active but I can only see the updation being done on value held by `a` that too which is a *local* variable – nits.kk Apr 18 '18 at 19:16
  • Classes can access their own private fields without getters and setters. – Compass Apr 18 '18 at 19:18
  • "_but it won't update my a value in main?_" You never updated `active` anywhere. "_I can simply use the setters, but I want to inside a function that I can call when I need to_" That's what a setter is, a method you call when you need to. Why is that not sufficient? – takendarkk Apr 18 '18 at 19:18
  • Can you provide us main method please. – Milos Apr 18 '18 at 19:19
  • 1
    Use Tell Don't Ask http://wiki.c2.com/?TellDontAsk – Martin Spamer Apr 18 '18 at 19:25

1 Answers1

3

You got the logic behind your login(int a) method wrong.

By calling login(2) you are passing the value (call-by-value) of 2 to the local variable a and then add b to it and it does work e.g. if you would print the value at the end:

public void login(int a) {
        int b = 2;
        a = b + a;
        System.out.println( a ); // this prints 4 if login(2) is called.
    }

To preserve this value you must either assign the new value to another variable e.g. active = a + b; or return the value so that the value is returned by the method and can be stored outherwise:

public int login(int a) {
        int b = 2;
        a = b + a;
        return a;
    }

This would allow you to do something like this in your main method:

public static void main( String[] args )
{
    Waiter wa = new Waiter();

    int stored = wa.login( 2 );
    System.out.println( stored ); // prints also 4
}
L.Spillner
  • 1,772
  • 10
  • 19