• 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
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

q from a mock exam

 
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Read the following code and can anybody explain how the code works
class Dumb{
Dumb(){
Object y = new X();
((X)y).m(y);
String in1 = y.toString();
}
public static void main(String[] args){
new Dumb();
}
}
class X {
public void m (Object x)
{
System.out.println("In m "+x);
}
public String toString()
{
System.out.println("ToSTring in Tostring");
return "123";
}
}
 
Rancher
Posts: 1449
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
This doesn't answer your question but the best way for you to learn what this does is code it up and throw some println's in to track where you are.
John
 
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Output:
ToSTring in Tostring
In m 123
ToSTring in Tostring
Reason:
operator+ is overriden to handle strings. i.e. if one of the operands is a string & the other a Object, then its
toString() method is called. Since we have overridden the toString method of Object class for class X,
this is invoked implicitly in the println() statement.
-Aj

[This message has been edited by Aj Patel (edited January 07, 2001).]
reply
    Bookmark Topic Watch Topic
  • New Topic