重写toString方法 [英] Overriding toString method
问题描述
我正在使用.toString返回对象的字符串表示形式,即
I am using .toString to return a string representation of an object, i.e.
jcb.engineMove(move.toString());
将产生e2e4.
我想做的是将这个对象(e2e4)的文本提取为字符串.谷歌搜索后,我遇到了重写toString方法的问题,所以我想到了:
What I am trying to do is to extract the text of this object (e2e4) as a string. After Googling I came across overriding the toString method so I came up with this:
@Override
public String toString() {
String s = "";
int newRank = getRank();
int newFile = getFile();
final Move move = new Move(rank, file, newRank, newFile);
s+="" + move;
return s;
}
我的问题很基本:
- 这是正确的方法
- 在尝试获取对象的文本时如何调用此例程?
推荐答案
覆盖 Object.toString
是一个好方法.
但是,您当前的实现通过创建一个新的 Move
对象(见下文)而犯了一个重大错误.
However, your current implementation makes a major mistake by creating a new Move
object (see below).
要调用例程(一旦您修复了该例程),请完全执行您已经在做的事情:
To call the routine (once you fix it), do exactly what you're already doing:
jcb.engineMove(move.toString());
如果 toString()
仅应用于调试(如mre所说),则可以实现另一个名为 getText
的方法,该方法具有相同的作用.
If toString()
should only be used for debugging (as mre says) you could implement another method named getText
that does the same thing.
重要提示:
您不应在其 toString
方法内创建一个新的 Move
对象.
You should not be creating a new Move
object inside its toString
method.
这是一个非常糟糕的主意(正如其他人提到的那样).
This is a very bad idea (as mentioned by others).
您的 toString
方法应该只构建一个字符串并将其返回.
Your toString
method should simply build a string and return it.
这篇关于重写toString方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!