Search code examples
javaclassoopgetter-setter

How to use variables in a different class in a new class


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
    }

EDITED:

public class Formulas {
    public static int rectangleFormula(Textview a, Textview b, Textview c, Textview d){
        Variables v= new Variables();
        int width = v.getWidth();
        int height = v.getHeight();
        int smallRectangle = width*height;
        int bigRectangle = smallRectangle*5;

        a.setText(Integer.toString(v.width()));
        b.setText(Integer.toString(v.height()));
        c.setText(Integer.toString(v.smallRectangle()));
        d.setText(Integer.toString(v.bigRectangle()));
        
    }

Solution

  • 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;
        }