• 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:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

using toString() method

 
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi all,
Can anyone tell me how do I use toString() in user defined class. When I tried to compile the following code I got an error:
import java.lang.*;
class MyClass
{
static int maxElements;
MyClass(int maxElements)
{
this.maxElements = maxElements;
}
}
public class Q19
{
public static void main(String[] args)
{
MyClass a = new MyClass(100);
MyClass b = new MyClass(100);
System.out.println(toString(a));
if(a.equals(b))
System.out.println("Objects have the same values");
else
System.out.println("Objects have different values");
}
}
Thanks in advance
Latha
 
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
will this work :-)

class MyClass
{
int maxElements;
MyClass(int maxElements)
{
this.maxElements = maxElements;
}
String toCompare(MyClass mc)
{
String newstr="";
if (this.maxElements==mc.maxElements)
{
newstr="Objects have same values";
}
else
{
newstr="Objects have differenet values";
}
return newstr;
}
}
public class Q19
{
public static void main(String[] args)
{
MyClass a = new MyClass(100);
MyClass b = new MyClass(1001);
System.out.println(a.toCompare(a));
System.out.println(a.toCompare(b));
}
}
 
Latha Kota
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This works excellent.Thank you, but I wanted to know if we can use toString() on a user defined class or not.
Latha
 
Ranch Hand
Posts: 443
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Latha Kota:


First of all, the toString() method of your class is the one inherited from the Object class. That method does not take any parameter.
Second, it is an instance method so you cannot use it inside a static method like main without a instance reference.
For your program to compile, you can invoke it like this:
System.out.println(a.toString());
 
reply
    Bookmark Topic Watch Topic
  • New Topic