public class Orc {
public static class A
{
public String getString()
{
return "this is A";
}
}
public static void main(String[] args)
{
A obj = new A();
System.out.println(obj);
System.out.println(obj.getString());
}
}
运行结果:
com.edu.cn.Orc$A@7852e922
this is A
class A
{
public String toString()
{
return "this is A";
}
}
public class tostringTest {
public static void main(String[] args) {
A obj = new A();
System.out.println(obj);
}
}
运行结果
this is A
toString的好处就是在碰到“println”之类的输出方法时会自动调用,不用显示打出来
public class User {
private String username ;
private String password ;
public User(){
}
public User(String username ,String password) {
this.username=username ;
this.password= password ;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String toString(){
return "姓名:"+username+"\t用户密码:"+password ;
}
public static void main(String[] args) {
System.out.println(new User("张三","123456"));
}
}
运行结果:
姓名:张三 用户密码:123456
class Villain {
private String name;
protected void set(String nm) {
name = nm;
}
public Villain(String name) {
this.name = name;
}
public String toString() {
return "I'm a Villain and my name is " + name;
}
}
public class add extends Villain{
private int orcNumber;
public add(String name, int orcNumber) {
super(name);
this.orcNumber = orcNumber;
}
public void change(String name, int orcNumber) {
set(name);
this.orcNumber = orcNumber;
}
public String toString() {
return "Orc" + orcNumber + ":" + super.toString();
}
public static void main(String[] args) {
add add = new add("Limburger", 12);
System.out.println(add);
add.change("Bob", 19);
System.out.println(add);
}
}
运行结果:
Orc12:I'm a Villain and my name is Limburger
Orc19:I'm a Villain and my name is Bob
在java中,如果一个对象未重写toString()方法,那么它将会调用父类的toString(),
如果父类也没有重写这个方法,那么就迭代往上调用,直到Object的toString()方法。因为它是Object里面已经有了的方法,而所有类都是继承Object,所以“所有对象都有这个方法”。
它通常只是为了方便输出,比如System.out.println(xx),括号里面的“xx”如果不是String类型的话,就自动调用xx的toString()方法
它是为了方便所有类的字符串操作而特意加入的一个方法