1

I have a class that contains some variables.Let's name it "Var" class. In "Var" class i have some variables like int width ,int height and so on. Some classes need this variables in order to work, also this variables are changing. My problem is, when i am creating an object of "Var" class in diffrent classes , each object contains its own int width and int height, and i dont want that.So, how to access variables from "Var" class from multiple classes?

john2994
  • 393
  • 1
  • 3
  • 15
  • make them public and static, that way all the classes can access them, and there is only one width/height for the entire program – Stultuske May 13 '20 at 11:55

1 Answers1

2

The easy solution would be to use the static modifier on the width and height variables to create only a single copy of the variables that belong to the class.

An alternative would be to create a single immutable reference to Var and compose other classes of the Var reference. This would encapsulate the fields of the Var class as well.

class Var {

    private final int width;

    private final int height;

    public Var(int width, int height) {
        this.width = width;
        this.height = height;
    }

    public int getWidth() {
        return width;
    }

    public int getHeight() {
        return height;
    }

}

Then you can have some class that depends on Var.

public class DependsOnVar {

    private final Var var;

    public DependsOnVar(Var var) {
        this.var = var;
    }

    public void someMethod() {
        int varWidth = var.getWidth();

        int varHeight = var.getHeight();

        // do something
    }

}
Jason
  • 5,154
  • 2
  • 12
  • 22