मुझे समझ में नहीं आ रहा है कि जब मैं तिमाही ऑब्जेक्ट पर 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();
}
}
आपको लगता है कि आपकी तिमाही वस्तु का स्ट्रिंग प्रस्तुति क्या है? आप अपने ऑब्जेक्ट को प्रिंट करने के लिए जावा को बस नहीं बता सकते हैं। – Mead3000