JAvaにおける属性への付与に関する2つの方法
4847 ワード
2つの方法の説明
1つのクラスのメンバー変数(属性)について、privateプライベートデータ型に設定されている場合、属性にgetメソッドとsetメソッドが対外的に設定、外部プログラムでこれらの属性に値を設定するには、2つの方法がある.1.set()メソッドにより.2.この属性を含む構造メソッドによりこの属性の値を直接設定.
コンストラクション関数は、このクラスをインスタンス化するときに属性に値を付与します.setは、インスタンス化時に値を付与したり変更したりしないときに使用され、getはクラスの属性を呼び出すときに使用されます.
プログラムの例
1つのクラスのメンバー変数(属性)について、privateプライベートデータ型に設定されている場合、属性にgetメソッドとsetメソッドが対外的に設定、外部プログラムでこれらの属性に値を設定するには、2つの方法がある.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());
}
}