-2

for the following problem:

fraction r1=new(1,2)
system.out.println(r1)

OUTPUT:

1/2

Does anyone know of a way to force the object to return a specific string rather than calling the object.toString() function and avoiding the output of something like class.fraction@xxxxx.

rid
  • 61,078
  • 31
  • 152
  • 193
  • 4
    Implement `toString()` in the Fraction class. – Paul Jun 18 '13 at 22:11
  • 1
    possible duplicate of [Java - How to create a println/print method for a custom class](http://stackoverflow.com/questions/8001664/java-how-to-create-a-println-print-method-for-a-custom-class) – trutheality Jun 18 '13 at 22:13

3 Answers3

6

When you call System.out.print(o) in Java, the toString() method of o is automatically called. Overwite this method in your fraction class and you should be good to go.

wlyles
  • 2,236
  • 1
  • 20
  • 38
3

You can always override toString():

@Override
public String toString(){
  return "This Object";
}

All Classes in the Java Platform are Descendants of Object, which is why any object of any class (even the ones you create) has access to Object's toString() method defined as follows:

public String toString(){
  getClass().getName() + '@' + Integer.toHexString(hashCode());
}

toString() gets called by default when you call System.out.println() but its just a regular inherited method and there is nothing stopping you from freely overriding it.

See this explanation on Oracle's website.

0x6C38
  • 6,796
  • 4
  • 35
  • 47
1

Override Object.toString() in your Fraction class

public class Fraction {

    private int numerator;
    private int denominator;

    public Fraction(int n, int d) {
        this.numerator = n;
        this.denominator = d;
    }

    @Override
    public String toString() {
        // String representation of Fraction
        return numerator + "/" + denominator;
    }
}

toString() is one of the few methods (like equals(), hashCode() etc.) that gets called implicitly under certain programmatic situations like (just naming a few)

  • printing an object using println()
  • printing a Collection of objects (toString() is invoked on all the elements)
  • concatenation with a String (like strObj = "My obj as string is " + myObj;)
Ravi K Thapliyal
  • 51,095
  • 9
  • 76
  • 89