我怎样才能像在 Python 和 __radd__ 中那样直接在 Java 中创建一个实例 return 字段的字符串?
How can I make an instance return the String of a field directly in Java as I could do in Python with __radd__?
在Python中,如果我想要一个实例直接return一个字段的字符串,我可以这样做:
class X:
def __init__(self, field):
self.field = field
self.__repr__ = self.__str__
def __radd__(self, other):
return other + self.field
def __str__(self):
return self.field
x = X("example.")
print("This is an " + x)
在Java,我不知道我会怎么做...
public class X {
public String field;
public X(String field) {
this.field = field;
}
}
public class Main {
public static void main(String[] args) {
X x = new X("example.");
System.out.println("This is an " + x.field); // Just x would return the address of the object in memory.
}
}
如果我理解你的问题,你可以 Override
toString
在 X
中使用
@Override
public String toString() {
return field;
}
那么你可以使用
System.out.println("This is an " + x);
这将隐式调用 toString
(例如等同于)
System.out.println("This is an " + x.toString());
您必须覆盖 toString()
方法:
public class X {
public String field;
public X(String field) {
this.field = field;
}
@Override
public String toString() {
return this.field;
}
}
在Python中,如果我想要一个实例直接return一个字段的字符串,我可以这样做:
class X:
def __init__(self, field):
self.field = field
self.__repr__ = self.__str__
def __radd__(self, other):
return other + self.field
def __str__(self):
return self.field
x = X("example.")
print("This is an " + x)
在Java,我不知道我会怎么做...
public class X {
public String field;
public X(String field) {
this.field = field;
}
}
public class Main {
public static void main(String[] args) {
X x = new X("example.");
System.out.println("This is an " + x.field); // Just x would return the address of the object in memory.
}
}
如果我理解你的问题,你可以 Override
toString
在 X
中使用
@Override
public String toString() {
return field;
}
那么你可以使用
System.out.println("This is an " + x);
这将隐式调用 toString
(例如等同于)
System.out.println("This is an " + x.toString());
您必须覆盖 toString()
方法:
public class X {
public String field;
public X(String field) {
this.field = field;
}
@Override
public String toString() {
return this.field;
}
}