2

I've been looking for the answer to this problem all day.

I have a value class that holds a variety of values as long as the program is running.

I create a new Value object in class A, and store an int value.
Class A also has a printMoney() method.

public class A {
Value value = new Value(); 
value.setMoney(100);

public void printMoney {
System.out.println(value.getMoney);
}

In class B, I want to be able to call printMoney() from class A, so logically I do the following:

public class B {
A a = new A();

a.printMoney();
}

This does, however, return '0' as a value instead of '100'.

I understand that by creating an A object, I automatically create a new value object, which has its default money value. So, basically my question is; how do I solve this?

2
  • What is value.getMoney? That's not a method call, and you haven't shown the code for your Value class. I suspect the problem is there. Commented Oct 14, 2013 at 14:37
  • 1
    Concur..the line value.setMoney(100); is outside a method and in the class header. Does this even compile? Commented Oct 14, 2013 at 14:41

3 Answers 3

5

Make the object static. static Value value = new Value();

  • static variables are shared across all the objects
  • So the change made in static variable will be reflected for all the objects of class.
Sign up to request clarification or add additional context in comments.

Comments

1

if you want to get that value in A you have to assign the value in A construtor, like

public class A {
  Value value = new Value();

  public A() {
     this.value.setMoney(100);
  }

otherwise, you can make the value static

1 Comment

I chose to make it static. Thanks for your answer.
0

you should receive the instance that creates the object B and save it then you would be able to call it like so:

public class A {
    B b = new B(this);
}

public class B {
    A a;

    public B(A a) {
        this.a = a;
    }

    private someMethod () {
        a.printMoney();
    }
}

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.