在Java面向?qū)ο缶幊讨?,類的屬性(也稱為成員變量)用于存儲對象的狀態(tài)信息。要設(shè)置類的屬性,您需要遵循以下步驟:
public class MyClass {
// 聲明屬性
private int myInt;
private String myString;
private boolean myBoolean;
}
public class MyClass {
// 聲明屬性
private int myInt;
private String myString;
private boolean myBoolean;
// 構(gòu)造函數(shù)
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;
// 構(gòu)造函數(shù)
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;
}
}
現(xiàn)在,您可以使用getter和setter方法設(shè)置和獲取屬性值,如下所示:
MyClass myObject = new MyClass(0, "Hello", true);
myObject.setMyInt(42);
int myIntValue = myObject.getMyInt();