【发布时间】:2011-12-18 23:44:21
【问题描述】:
我似乎无法理解为什么当我对季度对象使用 println 方法时,它会返回 toString 方法的值。我从来没有调用过 toString 方法为什么我得到了返回值?
public class Main {
public static void main(String[] args) {
Quarter q = new Quarter();
Nickel n = new Nickel();
System.out.println(q);
System.out.println(n);
}
}
public abstract class Money {
private int value;
public Money(int v) {
value=v;
}
public abstract int getValue();
protected int myValue() {
return value;
}
public abstract String toString();
}
public abstract class Coin extends Money {
public Coin(int value) {
super(value);
System.out.println("I am a coin, my value is " + getValue());
}
}
public class Quarter extends Coin {
public Quarter () {
super(25);
}
public int getValue() {
return myValue();
}
public String toString() {
return "A Quarter is "+getValue();
}
}
public class Nickel extends Coin {
public Nickel () {
super(5);
}
public int getValue() {
return myValue();
}
public String toString() {
return "A "+this.getClass().getName()+ " is "+getValue();
}
}
【问题讨论】:
-
您认为您的季度对象的字符串表示形式是什么?你不能只告诉 java 打印你的对象。