我最近了解了變數的 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()));
}
uj5u.com熱心網友回復:
如果您打算將該類Variables用作常量的共享存盤庫,則需要將所有欄位/方法宣告為static(類屬性)。否則,您必須首先創建該類的實體Variables v = new Variables()。只有這樣你才能使用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;
}
uj5u.com熱心網友回復:
您可以像這樣使用 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);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/463354.html
下一篇:Julia中OOP的替代方案
