Question

I am a newbie to Java (I come from the C/C++ background) and I was having a hard time figuring out how to allocated memory of a data member in one class from another. For eg,

Class A 
{
    B bInA;
    C cInA;

    public void foo(someValue)
    {
         cInA = new C();
         cInA.foo(bInA, someValue)
    }

    public static void main(String args[])
    {
         A myA = new A();
         myA.foo(xyz)

         // myA.bInA.value should be equal to xyz
    }
}

Class B { ... }

Class C 
{
    public void foo(bInA, someValue)
    {
          bInA = new B();
          bInA.value = someValue;
    }
}

Can I do something like this in java? Any help will be much appreciated.

----EDIT-----

Class A 
{
    B bInA;
    C cInA;

    public void foo(someValue)
    {
         cInA = new C();
         bInA = new B();
         cInA.foo(bInA, someValue)
    }

    public static void main(String args[])
    {
         A myA = new A();
         myA.foo(xyz)

         // myA.bInA.value should be equal to xyz
    }
}

Class B { ... }

Class C 
{
    public void foo(bInA, someValue)
    {
          bInA.value = someValue;
    }
}
Was it helpful?

Solution

Unless I'm misunderstanding your intention (change value of bInA from C), your recent edit seems to work fine. Here's my java version of your pseudocode.

class A 
{
    B bInA;
    C cInA;

    public void foo(int someValue)
    {
         cInA = new C();
         bInA = new B();
         cInA.foo(bInA, someValue);
         System.out.println(bInA.value);
    }

    public static void main(String args[])
    {
         A myA = new A();
         myA.foo(123);
         // myA.bInA.value should be equal to xyz
    }
}

class B { int value; }

class C 
{
    public void foo(B bInA, int someValue)
    {
          bInA.value = someValue;
    }
}

Output

123

OTHER TIPS

Java does not have pass-by-reference; rather, all you ever have are references to objects, and those references must be passed by value. So your code is roughly equivalent to something like this in C++:

class A {
  private:
    B *bInA = NULL;
    C *cInA = NULL;

  public:
    void foo(someValue) {
      cInA->foo(bInA, someValue);
    }

    static void main() {
      A *myA = new A();
      myA->foo(xyz)

      // myA->bInA->value should be equal to xyz
    }
}

int main() {
    A::main();
    return 0;
}

class B { ... }

class C {
  public:
    void foo(bInA, someValue) {
      bInA = new B(); // defeats the point of having passed in a bInA
      bInA->value = someValue;
    }
}

(Except that the C++ code has memory leaks, since you allocate some things without freeing them, whereas in Java that's not an issue.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top