当前位置: 动力学知识库 > 问答 > 编程问答 >

How to access the same object from multiple classes in Java

问题描述:

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?

网友答案:

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.
网友答案:

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

网友答案:

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();
    }
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: