简体   繁体   English

如何从默认构造函数中调用set方法?

[英]How do you call a set method from a default constructor?

I am working on an assignment that asks me to create "a default constructor and a second constructor that expects all three values to be passed as parameters. Call the “set” methods from both constructors" I have done the second constructor as follows; 我正在进行一项任务,要求我创建“默认构造函数和第二个构造函数,它要求所有三个值作为参数传递。从两个构造函数中调用”set“方法”我已经完成了第二个构造函数,如下所示;

public Cat(String newName, int newYearOfBirth, int newWieghtInKilos )
{
    setName(newName);
    setYearOfBirth(newYearOfBirth);
    setWeightInKilos(newWieghtInKilos); 
}

How do I create a default constructor that calls a set method? 如何创建调用set方法的默认构造函数?

The empty constructor can use setters with default values. 空构造函数可以使用具有默认值的setter。

public Cat()
{
    setName(defaultName);
    setYearOfBirth(defaultYearOfBirth);
    setWeightInKilos(defaultWieghtInKilos); 
}

You may tell the assignee that calling the set methods from both constructors is a wrong practice. 您可以告诉受让人从两个构造函数中调用set方法是错误的做法。 Your default constructor may happily use the parameter constructor with default values. 您的默认构造函数可能会愉快地使用带有默认值的参数构造函数。

public Cat(){
    this("",0,0);
}

This will help in code reusing. 这将有助于代码重用。

You can simply set the default values in the default constructor. 您只需在默认构造函数中设置默认值即可。

public Cat() {
    setName("MyName");
    setYearOfBirth(1987);
    setWeightInKilos(55);
}

Alternatively, you can also set empty values. 或者,您也可以设置空值。

You can call the setters from the default constructor in the same manner as you're doing in the overloaded constructor. 您可以使用与重载构造函数中相同的方式从默认构造函数中调用setter。

The only difference here is that in the default constructor you're not given any values to pass to the setters. 这里唯一的区别是,在默认构造函数中,您没有给任何值传递给setter。

However if you want those fields to be initialized with default values, you can invoke the setters with those default values. 但是,如果希望使用默认值初始化这些字段,则可以使用这些默认值调用setter。

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

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