分享

System.out.print()与toString()

 天天读书客家郎 2020-02-13
在Java里面,每一个类都会隐式地继承object类,而在object类里面有toString方法,这个就是用来输出类地地址。
System.out.println(this) 它会自动调用this对象的toString方法,所以若不重写toString方法地话,就会调用object类地toString方法,也就是输出当前对象的地址。
示例:

package test1;

public class Student {
    private int price;
    private String category;
    
    public int getPrice() {
        return price;
    }
    public void setPrice(int price) {
        this.price = price;
    }
    public String getCategory() {
        return category;
    }
    public void setCategory(String category) {
        this.category = category;
    }
    
    
    public Student(int price, String category) {
        this.price = price;
        this.category = category;
    }
//重写toString方法
    public String toString(){
        return "price:"+price+"category:"+category;
    }
}

输出Student
package test1;

public class StudentTest {

    public static void main(String[] args) {
        Student st=new Student(1,"category");
        System.out.print(st);
    }
}

结果 price:1category:category
若不重写toString方法则输出 test1.Student@142bece



    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多