需要mutator方法我该怎么做

时间:2013-10-15 22:46:05

标签: java

我正在做一个UML而且我不太确定如何做这些我应该这样做的mutator方法:

+turnOn(): void       //sets on to true
+turnOff(): void      //sets on to false
+channelUp(): void    //increases channel by 1 if on, rolls to 1 after maximum
+channelDown(): void  //decreases channel by 1 if on, rolls to maximum after 1
+volumeUp(): void     //increases the volume by 1 if on and less than maximum
+volumeDown(): void   //decreases volume by 1 if on and greater than 0
+toString( ): String  //returns the current state(instance variable values)

我的代码现在:(请记住mutator部分不对)

public class TV {
    private int volume;
    private int channel;
    private boolean on;
    private int maxVolume;
    private int maxChannel;

    TV() {
        volume = 1;
        channel = 1;
        on = false;
        maxVolume = 1;
        maxChannel = 1;
    }
    public int getChannel() {
        return channel;
    }

    public int getVolume() {
        return volume;
    }

    public boolean isOn() {
        return on;
    }

    public int getMaxChannel() {
        return maxChannel;
    }

    public int getMaxVolume() {
        return maxVolume;
    }
    public void setChannel(int i) {
        if (isOn() && i >= 1 && i <= maxChannel) channel = i;
    }

    public void setVolume(int i) {

        if (isOn() && i >= 0 && i <= maxVolume) volume = i;
    }

    public void setMaxChannel(int i) {
        maxChannel = i;
    }

    public void setMaxVolume(int i) {
        maxVolume = i;
    }

    // + turnOn() * * This is where the mutator methods begin I need help here * *

    // if (channel == maxChannel) channel = 1;
    // else channel++;

    //if (channel == 1) channel = max;
    //else channel--;

    // if (volume == maxVolume) volume = 1;
    // else channel++;
    //if (volume == 1) volume = max;
    // else channel--;

    public string toString() {
        return "channel: " + channel + "\nvolume: " + volume +
            "\non: " + on + "\nmax Channel: " + maxChannel +
            "\nmax Volume: " + maxVolume;
    }
}

3 个答案:

答案 0 :(得分:2)

Mutator通常意味着与'setter'相同的东西

所以在上面的代码中,'getter'将是:

public int getMaxChannel() {
  return maxChannel;
}

和'mutator'或'setter'将是:

public void setMaxChannel(int maxChannel) {
  this.maxChannel = maxChannel;
}

答案 1 :(得分:0)

我们可以互换使用setter和mutator。

  

mutator方法用于设置私有字段的值。它跟随   一个命名方案,在单词“set”前面加上方法的开头   名称。这些方法没有返回类型并接受参数   这是与其对应的私有字段相同的数据类型。该   然后使用参数来设置该私有字段的值。

以下是mutators或setter的一些例子:

public void setMaxChannel(int i) {
        maxChannel = i;
    }

public void setChannel(int c) {
        channel=c;
    }

答案 2 :(得分:0)

示例方法:

public void turnOn() {
   this.on = true;
}

public void channelUp() {
   if (on) {
      if (channel == maxChannel) {
         channel = 1;
      }
      else {
         channel++;
      }
   }
}

public void volumeDown() {
   if (on && volume > 0) {
      volume--;
   }
}

其他方法遵循相同的逻辑。

java中的字符串是对象,因此你的toString方法签名应该是public String toString()