首页 > 其他分享 >toString

toString

时间:2023-01-09 21:59:42浏览次数:42  
标签:String sal job toString public name

package com.EqualsExercise01;

public class Test {
    /*
    toString的默认返回:全类名 + @ + 哈希值的十六进制,
    子类往往重写toString方法 用于返回对象的属性
    public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }
    重写toString方法,打印对象或拼接对象时,都会自动调用该对象的toString形式。
    当直接输出一个对象时,toString方法会被默认调用

    */

    public static void main(String[] args) {
        Monster monster = new Monster("怪","走",7);
        System.out.println(monster.toString() + "\t" + monster.hashCode());

        System.out.println(monster);
    }
}

class Monster {
    private String name;
    private String job;
    private double sal;

    public Monster(String name, String job, double sal) {
        this.name = name;
        this.job = job;
        this.sal = sal;
    }

    @Override
    public String toString() {
        return "Monster{" +
                "name='" + name + '\'' +
                ", job='" + job + '\'' +
                ", sal=" + sal +
                '}';
    }
}

 

标签:String,sal,job,toString,public,name
From: https://www.cnblogs.com/shuqiqi/p/17038606.html

相关文章