-1

对于以下问题:

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

输出:

1/2

有谁知道强制对象返回特定字符串而不是调用 object.toString() 函数并避免输出类似 class.fraction@xxxxx 的方法。

4

3 回答 3

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.

于 2013-06-18T22:12:12.673 回答
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.

于 2013-06-18T22:11:55.870 回答
1

Object.toString()在您的Fraction班级中覆盖

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()是在某些编程情况下被隐式调用equals()的少数方法(如等hashCode())之一(仅举几个例子)

  • 使用打印对象println()
  • 打印一个Collection对象toString()在所有元素上调用)
  • 与字符串连接(如strObj = "My obj as string is " + myObj;
于 2013-06-18T22:15:07.603 回答