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