Saturday, February 25, 2012

Why-is-the-tostring-method-being-called-when-i-print-an-object

//Example why-is-the-tostring-method-being-called-when-i-print-an-object
//Because PrintStream.println has an overload that takes an Object, and then calls //itstoString method
public class ABC {
    public static void main(String[] args) {
        Coin1 q = new Quarter1();
        System.out.println("I am calling get value on coin " + q.getABC());
   
        System.out.println(q);
     
    }
}

  class Money1 {
    private int value;

    public Money1(int v) {
        value=v;
    }

    public  int getValue()
    {
    return value;
    }

    protected int myValue() {
        return value;
    }

    public  String toString()
    {
    return "Anand";
  }
}

  class Coin1 extends Money1 {
    public Coin1(int value) {
        super(value);
        System.out.println("I am a coin, my value is " + getValue());
    }
 
    public int getABC() {
        return 23;
    }

}

 class Quarter1 extends Coin1 {
    public Quarter1 () {
        super(25);
    }

    public int getValue() {
        return myValue();
    }

    public String toString() {
        return "A Quarter is "+getValue();
    }
}

No comments:

Post a Comment