java中關於給屬性賦值的兩種方法
阿新 • • 發佈:2019-01-22
兩種方法說明
對於一個類中的成員變數(屬性),如果都被設定成了private私有資料型別,則對外給屬性設定了get和set方法 ,
外部程式中給這些屬性設定值,有兩種方式.
1.通過set()方法.
2.通過含有這個屬性的構造方法來直接設定這個屬性的值.
建構函式就是在例項化這個類的時候給屬性賦值.
set是在例項化時沒有賦值或者改變值的時候用,get是呼叫類中屬性的時候用
程式舉例
package java1;
public class Fan {
int SLOW = 1;
int MEDIUM = 2 ;
int FAST = 3;
int speed = SLOW;
boolean on = false;
double radius = 5;
String color = "blue";
int getSpeed() {
return speed;
}
boolean getOn() {
return on;
}
double getRadius() {
return radius;
}
String getColor() {
return color;
}
//set()設定值方法
public void setOn(boolean on) {
this.on = on;
}
public void setRadius(double radius) {
this.radius = radius;
}
public void setSpeed (int speed) {
this.speed = speed;
}
public void setColor(String color) {
this.color = color;
}
public Fan() {
}
//構造方法賦值
public Fan(int speed,double radius,String color,boolean on) {
this.speed = speed;
this.radius = radius;
this.color = color;
this.on = on;
}
//toString方法返回字串描述
public String toString() {
if(on==true){
return "該風扇的速度為:" + speed +";顏色是:"+color+";半徑是:"+radius;
}
else{
return "fan is off;"+"該風扇的顏色是:"+color+";半徑是:"+radius;
}
}
public static void main(String[] args) {
Fan fan1 = new Fan(3,10,"yellow",true);
Fan fan2 = new Fan(2,5,"blue",false);
System.out.println(fan1.toString());
System.out.println(fan2.toString());
}
}