Win a copy of Five Lines of Code this week in the OO, Patterns, UML and Refactoring forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Liutauras Vilda
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • fred rosenberger
  • salvin francis
Bartenders:
  • Piet Souris
  • Frits Walraven
  • Carey Brown

q from a mock exam

 
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • 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
  • 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
  • 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).]
 
The glass is neither half full or half empty. It is too big. But this tiny ad is just right:
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
    Bookmark Topic Watch Topic
  • New Topic