Bob Goblin
Bob Goblin

Reputation: 1269

Java -- Pass variable from class to class

I know that to pass from within the Same class, I would do something like this --- but what about between classes?

class TestMe{
    public static void main(String[] args)
    {
        int numberAlpha = 232;
        TestMe sendNumber = new TestMe();
        sendNumber.Multiply(numberAlpha);
    }

    void Multiply(int var)
    {
        var+=40;
    }
}

Upvotes: 3

Views: 65222

Answers (1)

Xabster
Xabster

Reputation: 3720

You use getters and setters.

class A {
    private int a_number;
    public int getNumber() { return a_number; }
}
class B {
    private int b_number;
    public void setNumber(int num) { b_number = num; }
}

.. And in your main method, wherever it is:

public static void main(String[] args) {
    A a = new A();
    int blah = a.getNumber();
    B b = new B();
    b.setNumber(blah);
}

You can also use constructors as a means of an "initial setter" so that the object is always created with a minimum set of variables already instantiated, for example:

class A {
    private int a_number;
    public A(int number) { // this is the only constructor, you must use it, and you must give it an int when you do
        a_number = number;
    }
    public int getNumber() { return a_number; }
}

Upvotes: 10

Related Questions