• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

Qs about toString()

 
Ranch Hand
Posts: 348
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
Could some one explain why the overriding toString() in class A1 was not called as it is being called on class B1?
note : A1, B1 on different files.
thanks
chi-chih
class A1 {
public static void main(String args[]) {
Integer a = new Integer(7);
System.out.println("A1 : "+ a);
}

public String toString () {
return " from toString()in A1";
}
}
class B1 {
public static void main(String args[]) {
Integer b = new Integer(7);
System.out.println("B1 : "+ new B1()+b);
}

public String toString () {
return " from toString() in B1";
}
}
 
Ranch Hand
Posts: 625
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The overridden method toString() is not called in A1 because you override it in class A1 and you never instantiate a A1 object. Instead you instantiate an Integer object so it's toString method is called.
In the B1 class you create an instance, so that instance uses it's overridden toString method to covert itself to a String.

[This message has been edited by Sean Casey (edited September 08, 2001).]
 
chi Lin
Ranch Hand
Posts: 348
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Sean,
Thank you for the explanation.
chichih
 
reply
    Bookmark Topic Watch Topic
  • New Topic