2

java n00b here.

I have a custom Data type defined like this:

public class MyData{
    int value;
    int type;
    String name;

    public MyData(int newValue, int newType, string newName)
    {
        value = newValue;
        type  = newType;
        name  = newName;
    }
}

When I call an instance of this class, I want it to evaluate to the value property, like this:

myData dataInstance = new myData(100,3,"customData");
System.out.println(dataInstance); // should print "100"

Can this be achieved?

Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
  • possible duplicate of [How to use the toString method in Java?](http://stackoverflow.com/questions/3615721/how-to-use-the-tostring-method-in-java) – Nix Mar 18 '13 at 13:21
  • Yes use the toString method. Also class level fields should normally be declared private (e.g. private int value;) – cowls Mar 18 '13 at 13:22
  • 1
    Fix your sytnax errors (`String` instead of `string`), follow the Java naming conventions (`MyData` instead of `myData`) and override the `toString()` method. Then it will be achieved. – jlordo Mar 18 '13 at 13:23
  • @jlordo pardon my ignorance, I usually never code in Java – Mathias R. Jessen Mar 18 '13 at 13:28

1 Answers1

7

When you use System.out.println with an object, it's going to call the toString() method - so you just need to override that:

@Override public String toString() {
    return String.valueOf(value);
}

Also note that you should be more specific in your terminology. When you wrote:

When I call an instance of this class

... that doesn't mean anything. You don't call an instance - you call a method on an instance. In this case, the method is toString.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • So, I can't just reference the instance, and have a "catch-all" method execute that way? Overriding `toString()` seems like a fine solution, but what I'm looking for is, not having to explicitly call a method on the instance. – Mathias R. Jessen Mar 18 '13 at 13:25
  • 2
    @MathiasR.Jessen: As Jon explained, if you override `toString()`, you don't have to explicitly call it, it will be done automatically by `System.out.println(dataInstance);` – jlordo Mar 18 '13 at 13:28
  • Thanks for this method, to be more clear, just add this override method in your customized class. – stoneshishang Oct 28 '21 at 15:09