【问题标题】:How to define default & non-default constructors, along with mutator and accessor methods如何定义默认和非默认构造函数,以及 mutator 和 accessor 方法
【发布时间】:2018-09-06 13:58:42
【问题描述】:

在这里创建一个基本类(学生),需要帮助确认默认和非默认构造函数是否正确定义以及如何实现 mutator 和 accessor 方法。

public class STUDENT
{
    private String name;
    private String address;
    private String phone_no;
    private String email;

    /**
     * Default constructor for objects of class STUDENT
     */
    public STUDENT()
    {
        name = "";
        address = "";
        phone_no = "";
        email = "";
    }

    /**
     * Non-default constructor for objects of class STUDENT
     */
    public STUDENT (String newName, String newAddress, String newPhone_no, String newEmail)
    {
        name = newName;
        address = newAddress;
        phone_no = newPhone_no;
        email = newEmail;
    }

    /**
     * The mutator method (set) for the field of name.
     */
    public void setName(String name)
    {
        name
    }

    /**
     * The accessor method (get) for the field of name.
     */
    public String getName()
    {
        return
    }
}

【问题讨论】:

  • 构造函数中的一切看起来都很好。对于 setter 方法,您只需将全局变量设置为等于参数中的变量。对于 getter 方法,您只需返回具有相同名称的全局变量。我不太确定您还可能在这里问什么

标签: bluej


【解决方案1】:

就构造函数而言,是的,它们已被正确定义。只要构造函数的“签名”是分开的,那么类就会编译。

关于访问器(get)和修改器(set)方法,使用如下:

访问者:

public void getName()
{
   return name;
}

突变体:

public String setName(String name)
{
   this.name = name;
}

遵循这将有助于您的代码:)

【讨论】:

    猜你喜欢
    • 2015-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-30
    • 1970-01-01
    • 2016-02-05
    • 1970-01-01
    • 2016-07-23
    相关资源
    最近更新 更多