gpt4 book ai didi

java - 这两种方法有什么区别

转载 作者:行者123 更新时间:2023-11-30 02:00:30 25 4
gpt4 key购买 nike

这两种方法计算单项的导数,但我不明白它们之间有什么区别,它们做同样的事情吗?为什么一个有返回,另一个对调用对象进行更改?哪一个更好?一般来说,我应该如何返回对象?

public Monom Der()
{
double a = this.get_coef() * this.get_pow();
int b = this.get_pow() - 1;
return new Monom(a, b);
}

public void Der()
{
this.set_coefficient(this._power * this._coefficient);
this.set_power(this._power - 1);
}

最佳答案

这个

public Monom Der() {
double a = this.get_coef() * this.get_pow();
int b = this.get_pow() - 1;
return new Monom(a, b);
}

不会改变实例的状态,当你想要拥有不可变的对象时它很有用。它可用于处理初始状态和处理后状态

Monom initialMonom = new Monom(2, 2);
Monom theNewMonom = initialMonom.Der();
// do something with both initialMonom and theNewMonom

这个

public void Der() {
this.set_coefficient(this._power * this._coefficient);
this.set_power(this._power - 1);
}

更改当前实例的状态,因此该实例不是不可变的。当实例需要重用时它会很有用

Monom initialMonom = new Monom(2, 2);
// do something with initial monom
initialMonom.Der(); // mutate the initial monom
// do something with the new state

关于java - 这两种方法有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53010326/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com