一直没注意String类的valueOf(Object obj)方法也可以将object对象转换为String,我用老代码实验了一下:- public class test {
-
- public static void main(String[] args)throws Exception {
- person p1 = new person("ming",23);
- System.out.println(String.valueOf(p1));
-
- }
- }
- class person {
- private String name;
- private int age;
- public person(String name,int age) {
- this.name = name;
- this.age = age;
- }
- public void smile(){
- System.out.println("hehe");
- }
- public void laugh(){
- System.out.println("heihei");
- }
- public String toString(){
- return name+":"+age;
- }
- }
复制代码 结果是:ming:23
发现它和p1.toString()的结果是一样的,那String.valueOf()方法和toString方法有什么联系,使用上有区别呢?1 |