如何在新类中使用不同类中的变量



我最近学习了变量的getter和setter,所以我想利用它。我为使用getter和setter的变量创建了一个单独的类。我想在另一个包含公式的类中使用我在这门课中创建的变量。如何使用公式类中的变量?

这是我的变量类:
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;
}

这些是应该在公式类中的公式(这不起作用)

public class Formulas {

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

编辑:

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()));

}

如果您打算使用类Variables作为常量的共享存储库,则需要将所有字段/方法声明为static(类属性)。否则,您必须首先创建该类Variables v = new Variables()的实例。只有这样才能使用v.getWidth()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;
}

你可以像这样使用getter和setter。

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

}

最新更新