public class Fan {
public static void main(String[] args){
Fan fan1 = new Fan();
fan1.setSpeed(FAST);
fan1.setRadius(10);
fan1.setColor("yellow");
fan1.setOn(true);
System.out.println(fan1.toString());
}
// fan speed variables
final static int SLOW = 1;
final static int MEDIUM = 2;
final static int FAST = 3;
// Other fan variables
private int speed;
private boolean on; // true means on
private double radius; // radius of fan
String color;
// No-arg constructor
public void Fan(){
speed = SLOW;
on = false;
radius = 5;
color = "blue";
}
// Mutator methods
public void setSpeed(int newSpeed){
if(newSpeed < 0)
System.out.println("Illegal speed!");
else
speed = newSpeed;
}
public void setOn(boolean newOn){
on = newOn;
}
public void setRadius(int newRadius){
if(newRadius < 0)
System.out.println("Illegal radius!");
else
radius = newRadius;
}
public void setColor(String newColor){
color = newColor;
}
// Accessor methods
public int getSpeed(){
return speed;
}
public boolean getOn(){
return on;
}
public double getRadius(){
return radius;
}
public String getColor(){
return color;
}
// toString method to output Fan data
public String toString(){
if(on = false)
return "Fan is off.";
else
return "Fan Properties:\n" + "Fan speed: " + speed + "\n"
+ "Color: " + color + "\n"
+ "Radius: " + radius + "\n";
}
}
上面的代码很简单,但我想知道toString方法如何使用on变量,即使我没有为该方法提供参数。另外,为什么我们不需要在主类中调用get方法而只需要调用set方法? (请解释每种方法如何在最终输出之前互相调用)
非常感谢!
答案 0 :(得分:1)
就你在这个类体中而言,你可以访问所有东西(除了静态不能访问非静态)。这意味着您可以轻松设置和获取类似的变量:
var = <value>;
System.out.println(var);
但是没有人阻止你使用访问者方法 - getter和setter。这不是必需的。
最后一点说明:
if(on = false)
这将始终失败 - 它将赋值为false,然后检查新分配的值(为false)。你需要在这里检查是否平等。像那样:
if(on == false)
甚至更好:
if(!on)
答案 1 :(得分:0)
我只是将您的代码复制粘贴到一个新文件中并进行编译。它编译并运行。输出是
$ java Fan
Fan Properties:
Fan speed: 3
Color: yellow
Radius: 10.0
这是因为toString
方法中的比较是错误的。它应该如下:
public String toString(){
if(on)
return "Fan Properties:\n" + "Fan speed: " + speed + "\n"
+ "Color: " + color + "\n"
+ "Radius: " + radius + "\n";
else
return "Fan is off.";
}