Home > Back-end >  How to use variables in a different class in a new class
How to use variables in a different class in a new class

Time:04-18

I recently learned about getters and setters for variables so I wanted to make use of it. I created a separate class for the variables which uses getters and setters. I would want to use the variables I made in this class in a different class that contains formulas. How do I use the variables in the Formulas class?

This is my variables class:

public class Variables {

    private int width, height, smallRectangle, bigRectangle;

    //getters
    public int getWidth() {
        return width;
    }

    public int getHeight() {
        return height;
    }

    public int getSmallRectangle() {
        return smallRectangle;
    }

    public int getBigRectangle() {
        return bigRectangle;
    }

    //setters

    public void setWidth(int width) {
        this.width = width;
    }

    public void setHeight(int height) {
        this.height = height;
    }

    public void setSmallRectangle(int smallRectangle) {
        this.smallRectangle = smallRectangle;
    }

    public void setBigRectangle(int bigRectangle) {
        this.bigRectangle = bigRectangle;
    }

and these are the formulas that should be in the formulas class (this does not work)

public class Formulas {
    
    public static int rectangleFormula(){
        smallRectangle=width*height;
        bigRectangle=smallRectangle*5
    }

CodePudding user response:

If you intend to use the class Variables as a shared repository of constant, you will need to declare all the fields/methods as static (class properties). Otherwise, you'll have to create an instance of that class Variables v = new Variables() first. Only then can you use v.getWidth() and v.setWidth().

public class Formulas {
    
    public static int rectangleFormula(Variables v){
        int width = v.getWidth();
        int height = v.getHeight();
        int smallRectangle = width*height;
        int bigRectangle = smallRectangle*5;
    }

CodePudding user response:

You can use getters and setters like this.

public class Formulas {

public static int rectangleFormula(){
    
    Variables v = new Variables();
    v.setWidth(5);
    v.setHeight(10);
    int smallRectangle=v.getWidth() * v.getHeight();
    int bigRectangle=smallRectangle*5;
    System.out.println("smallRectangle: "   smallRectangle   
                       "\nbigRectangle:"   bigRectangle);
}

}

  • Related