3

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;
    }
}
5
  • 1
    create an instance and pass the variable using the appropriate instance method. please read Classes and Objects. Commented Aug 12, 2013 at 19:02
  • 1
    Look up the JavaDocs and objects/methods Commented Aug 12, 2013 at 19:04
  • 2
    That's... an odd way to "pass a variable in the same class". Can Multiply not be made static? As for your question in general, it might be easier if you distinguish between "class" and "object." You're not passing a variable "to the same class." You're create an object of type TestMe and calling a function on it. You can create an object of any other type you'd like and call a function on that exactly the same way. Commented Aug 12, 2013 at 19:04
  • 2
    You definitely need to look for a nice reading about general and then object oriented programming. Commented Aug 12, 2013 at 19:04
  • Your question is unclear. Is it about passing by reference? Commented Aug 12, 2013 at 19:05

1 Answer 1

10

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; }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.