public class potpie {
public int month;
public int day;
public int year;
public static void main(String[] args) {
potpie potObject = new potpie(4,5,6);
}
public potpie(int m, int d, int y){
month = m;
day = d;
year = y;
System.out.printf("The constructor for this is %s\n", this);
}
public String toString(){
return String.format("%d/%d/%d", month, day, year);
}
}
我正在观看有关Java的视频教程,他编写了这段代码。但是我不明白他对为什么要打印出来的解释
The constructor for this is 4/5/6
我只是不明白为什么要使用方法toString?
的this
位于所述构造内是指“被构造”当前对象,一个potpie
。
该系统输出功能自动调用上传入的对象的toString()方法。如果对象的类未覆盖该toString
方法,则您可能会获得Object
类似的版本"classname@HexNumber"
。
// Behind the scenes
System.out.printf("The constructor for this is %s\n", this.toString());
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句