How to override toString() - Programmers Heaven

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

How to override toString()

VashudevVashudev Posts: 28Member
Hi!
I need to override toString() method to print the name of the object. I am assigning the "this" variable in a method to a string object(str = this.toString() and printing the name of the object using System.out.prinln(str) but doing that also prints some hex code and @ sing, I asked this question before somewhere else but the replies weren't very understnadable.
Please help
Thanks!

Comments

  • zibadianzibadian Posts: 6,349Member
    : Hi!
    : I need to override toString() method to print the name of the object. I am assigning the "this" variable in a method to a string object(str = this.toString() and printing the name of the object using System.out.prinln(str) but doing that also prints some hex code and @ sing, I asked this question before somewhere else but the replies weren't very understnadable.
    : Please help
    : Thanks!
    :
    You can override that like any other overriden method:
    [code]
    class HelloWorld {

    public String toString() {
    return 'Hello World!';
    }

    }
    [/code]

  • armadilloFuncarmadilloFunc Posts: 1Member
    You're really looking for a way to access the name of the variable that refers to your object. This is not straightforward in Java.

    I've found something that may be useful in looking for 'Introsector' on the sun website.

    Good luck!
  • j2me64j2me64 Posts: 20Member

    inside your class you could use something like

    [code] public String toString() {
    return this.getClass().getName();
    }[/code]

    which will return the name of the class.
  • xanadu72xanadu72 Posts: 1Member
    Find in this [link=http://www.java-tutorial.ch/architecture/tostringbuilder-style]article about ToStringBuilder[/link] an elegant way and some explanation on how to return the toString value
  • sabhandarisabhandari Posts: 1Member
    toString is mostly used when you try to print a class's object using System.out.println and pass the object as a parameter to this function. I think if one makes a habit to always override toString method then only all classes in application will allow printing important information about object using SOP How to implement toString method in Java
Sign In or Register to comment.