-1

I'm new to Java and I'm learning the language fundamentals.

Can someone explain to me how the toString method is called when there is no function call to it? I think it has something to do with the actual enumerator words on the second line such as:

KALAMATA("Kalamata"), LIGURIO("Ligurio") ...

The whole purpose for this enum class is so the ENUM values don't print to screen in all upper case characters.

Can someone please explain me how toString method is used in this class? Like when is it called? How is it called?

public enum OliveName {

    KALAMATA("Kalamata"),LIGURIO("Ligurio"),PICHOLINE("Picholine"),GOLDEN("Golden");

    private String nameAsString;

    //for enum classes, the constructor must be private
    private OliveName(String nameAsString) {
        this.nameAsString = nameAsString;
    }

    @Override
    public String toString() {
        return this.nameAsString;
    }
}
mosawi
  • 1,283
  • 5
  • 25
  • 48

1 Answers1

0

Pretty much like any object.

OliveName oliveName = OliveName.KALAMATA;
System.out.println(oliveName.toString());

or

System.out.println(oliveName);
wvdz
  • 16,251
  • 4
  • 53
  • 90
  • I don't understand how you can just Sysout(oliveName); and the toString method is implicitly called? – mosawi Jul 07 '14 at 00:46
  • 1
    @mosawi Look at the [implementation of `println()`](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/io/PrintStream.java#PrintStream.println%28java.lang.Object%29). Your question doesn't really have to do with enums themselves... – awksp Jul 07 '14 at 00:48
  • 1
    This is done by the println() method: http://docs.oracle.com/javase/7/docs/api/java/io/PrintStream.html#println%28java.lang.Object%29 – wvdz Jul 07 '14 at 00:49
  • okay so what I gather is that because the println method first looks for a string value representation of the object passed to it, once it gets that string value, then it prints to screen? The string value of the object is the string literal as specified in the class. Am I almost correct? – mosawi Jul 07 '14 at 01:06
  • 1
    @mosawi Close. The string value of a non-null object is whatever is returned by the `toString()` method, so in this case, yes, it's the literal you specified. – awksp Jul 07 '14 at 01:08
  • @user3580294 I think I got it. So does this mean the toString method is a core method, automatically called by the JVM? This would explain why we override the method to begin with – mosawi Jul 07 '14 at 01:28
  • 1
    @mosawi Well, not quite. It's called because that's what the code tells the JVM to do -- `String.valueOf()` is implemented such that it returns `"null"` if the object is `null` and `toString()` otherwise. I'm not really sure what you mean by "core method" -- the JVM is just doing what the code tells it to do. – awksp Jul 07 '14 at 02:51