在Java面向對象編程中,類的屬性(也稱為成員變量)用于存儲對象的狀態信息。要設置類的屬性,您需要遵循以下步驟:
public class MyClass {
// 聲明屬性
private int myInt;
private String myString;
private boolean myBoolean;
}
public class MyClass {
// 聲明屬性
private int myInt;
private String myString;
private boolean myBoolean;
// 構造函數
public MyClass(int myInt, String myString, boolean myBoolean) {
this.myInt = myInt;
this.myString = myString;
this.myBoolean = myBoolean;
}
}
myInt
屬性的值,您可以使用以下代碼:MyClass myObject = new MyClass(0, "Hello", true);
myObject.myInt = 42;
public class MyClass {
// 聲明屬性
private int myInt;
private String myString;
private boolean myBoolean;
// 構造函數
public MyClass(int myInt, String myString, boolean myBoolean) {
this.myInt = myInt;
this.myString = myString;
this.myBoolean = myBoolean;
}
// getter和setter方法
public int getMyInt() {
return myInt;
}
public void setMyInt(int myInt) {
this.myInt = myInt;
}
public String getMyString() {
return myString;
}
public void setMyString(String myString) {
this.myString = myString;
}
public boolean isMyBoolean() {
return myBoolean;
}
public void setMyBoolean(boolean myBoolean) {
this.myBoolean = myBoolean;
}
}
現在,您可以使用getter和setter方法設置和獲取屬性值,如下所示:
MyClass myObject = new MyClass(0, "Hello", true);
myObject.setMyInt(42);
int myIntValue = myObject.getMyInt();