System.out.print()与toString()

在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



转载于:https://www.cnblogs.com/Lanyuxuan/p/5235949.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值