我可以创建自定义类对象并使它们的行为方式相同吗?例如 -
如果我有课:
class MyCustomClass{
int myDisplayValue;
public MyCustomClass(int value){
this.myDisplayValue = value;
}
}
我用它作为:
class TestClass{
public static void main(String[] args){
MyCustomClass testObj1 = new MyCustomClass(8);
System.out.println(testObj1); // prints the class name with some random text
Integer testObj2 = new Integer(8);
System.out.println(testObj2); // prints the int value '8'
}
有没有办法让testObj1打印' 8'还有?我意识到这可能没有任何用处,还有其他方法可以更安全地打印价值,我只是想知道这是否可行。
答案 0 :(得分:0)
覆盖toString方法并返回整数的字符串。
@Override
public String toString(){
return String.valueOf(myDisplayValue);
}