我正在进行一项任务,我必须创建另一个类扩展的父类,我必须在父类中过度使用toString()方法,并使用父toString方法显示新的,但是添加一行。
所有我都很好,但是在我被卡住的地方,原来的toString()有一个数字格式对象,它将double格式化为金钱,我需要在新行中格式化一个double。说明说我不应该在新的toString方法中使用数字格式化器,并且让旧的toString()方法处理“大部分工作”,但我无法弄清楚如何格式化这个双。
这是一些代码,所以你可以看到我的意思:
import java.text.NumberFormat;
public abstract class First {
public First(int x, double y)
protected int num = x;
protected double num2 = y;
}
public String toString()
{
NumberFormat x = NumberFormat.getCurrencyInstance();
return "Int num: " + num +
"\n num2: " + x.format(num2);
}
}
然后我有了孩子班:
public class Second extends First {
protected double num3;
public Second(int x, double y, double z)
{
super(x, y);
num3 = z
}
public String toString()
{
return super.toString() + "\n num3 " + num3;
}
}
如果我这样做(我遗漏了很多不相关的代码)它可以工作,但我需要将num3格式化为money,就像num2在父类中一样,但我不能在子类中有一个formatter对象
如果有人能把我推向正确的方向,我会非常感激。
答案 0 :(得分:2)
您可以将格式设置与父类中的toString()
方法分开,然后在您的孩子中使用它,如:
在第一次
protected String formatNum(double number)
{
NumberFormat x = NumberFormat.getCurrencyInstance();
return x.format(number);
}
public String toString()
{
return "Int num: " + num +
"\n num2: " + formatNum(num2);
}
然后在第二个
public String toString()
{
return super.toString() + "\n num3 " + formatNum(num3);
}
编辑另一种方法是将NumberFormat
对象作为First
对象的一部分,然后在构造函数中初始化
public abstract class First {
protected int num;
protected double num2;
protected NumberFormat f;
public First(int x, double y)
{
num = x;
num2 = y;
f = NumberFormat.getCurrencyInstance();
}
public String toString()
{
return "Int num: " + num +
"\n num2: " + f.format(num2);
}
}
然后在Second
public String toString()
{
return super.toString() + "\n num3 " + f.format(num3);
}
答案 1 :(得分:0)
如果没有检查,NumberFormat.getCurrencyInstance()可能返回一个单例,因此调用它作为父进程,不会导致另一个对象,但与父使用相同的对象...也许是一个有趣的问题:)。< / p>