对于以下问题:
fraction r1=new(1,2)
system.out.println(r1)
输出:
1/2
有谁知道强制对象返回特定字符串而不是调用 object.toString() 函数并避免输出类似 class.fraction@xxxxx 的方法。
对于以下问题:
fraction r1=new(1,2)
system.out.println(r1)
输出:
1/2
有谁知道强制对象返回特定字符串而不是调用 object.toString() 函数并避免输出类似 class.fraction@xxxxx 的方法。
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.
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.
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;
)