java——Object覆写toString

2019年2月16日12:14:19 发表评论 979 views

覆写前:

/**
 * Created by xabcd on 2019/2/16.
 */

    class total_print extends Object{
        String name = "张三:" ;
        int age = 25;
    }


/**
 * Created by xabcd on 2019/2/16.
 */
public class test_print
{
        public static void main(String args[])
        {
            total_print p = new total_print();
            System.out.println(p);
        }

}



结果:
total_print@4554617c




覆写后:
/**
 * Created by xabcd on 2019/2/16.
 */

    class total_print extends Object{
        String name = "张三:" ;
        int age = 25;
    public String toString()
    {
        return"我是:"+this.name+",今年:"+this.age+"岁";
    }
    }





/**
 * Created by xabcd on 2019/2/16.
 */
public class test_print
{
    public static void main(String args[])
    {
        total_print p = new total_print();
//此时本行相当于  System.out.println(p.toString());
        System.out.println(p);
    }

}
结果: 我是:张三:,今年:25岁

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: