繁体   English   中英

编写mutator方法

[英]Writing a mutator method

修改mutator方法的定义

编写一个变数方法setAge(),该方法采用一个int类型的单个参数并设置变量age的值。在此处粘贴您的答案:

public int setAge(int age) 
{
   return age;
}

评论:

* Test 1 (0.0 out of 1)

      The compilation was successful
      The output should have been:
          setAge() Correct

      This is what was actually produced:
          setAge() not Correct

为什么我会收到此错误感到困惑,是因为在setAge之后我有(int age)这就是为什么错误会出现的原因?

mutator实际上没有设置任何内容。

我假设您已经有一段代码需要修改,请在那段代码中搜索变量/字段“ age”。

试试看

public void setAge(int age) 
{
  this.age = age;
}

您的代码不会“设置可变年龄的值”。 您的方法仅返回传递给它的值。

假设您有一个名为'age'的类变量,则可以按以下方式创建mutator类方法:

public class myTest{

public int age;

//other code here..if any

public void setAge(int age) 
{
  this.age = age;
}

//other code here.. if any
}

通常,您的setAge方法不应返回任何内容。 Mutator仅修改值。

要返回值,您应该使用称为“访问器”的getAge()方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM