0

I want to have a setter and getter for root word by passing and returning an object of type Word:

class Master {
    Word word = new Word();

    word.setName("eating");
    word.setRootWord(new Word("eat"));

    System.out.println(word.getRootWord().toString());
}


class Word {
    private String name;
    private Word rootWord, synonyms, antonyms;

    public Word () {

    }

    public Word (String name) {
        this.name = name;
    }

    public setName (String name) {
        this.name = name;
    }

    public getName () {
        return this.name;
    }

    public setRootWord (Word rootWord) {
        this.rootWord = rootWord;
    }

    public getRootWord () {
        return this.rootWord;
    }
}

What gets printed is something like Word@42a57993

How can I get eat printed on the screen? or a better way of doing this?

VMAtm
  • 27,943
  • 17
  • 79
  • 125

4 Answers4

2

I think that the problem is in this line:

System.out.println(word.getRootWord().toString());

Switch it to:

System.out.println(word.getRootWord().getName());

Or, as other option, you can override your toString() method for a word class, something like this:

class Word {
     public override String toString(){
        return this.getName();
     }
}

Word@42a57993 is a class name for your object, and this is a default implementation of a toString method in Java as the compiler and object class doesn't know anything about the object except the type of it.

VMAtm
  • 27,943
  • 17
  • 79
  • 125
0

You need to override the toString method of the object class

SomeJavaGuy
  • 7,307
  • 2
  • 21
  • 33
0

To stop that rather arbitrary text from being printed, you could override java.lang.Object#toString() for your class Word.

toString() is used by Java to output a string representation of the object. It doesn't have to be a true serialisation in the sense that the mapping should be unique, but just an adequate textural representation. Many debuggers will call this method to display an object's state as a tooltip.

To print eat, make a call to word.getRootWord().getName().

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
0

Use this:

System.out.println(word.getRootWord().getName());
Jens
  • 67,715
  • 15
  • 98
  • 113