重写toString()方法
package com.jian.demo7;
public class Car extends Object {
//编写实例变量
String id;
String brand;
String color;
int price;
public Car() {
}
public Car(String id, String brand, String color, int price) {
this.id = id;
this.brand = brand;
this.color = color;
this.price = price;
}
//第一种方式:光标放在子类中,按Ctrl + O选择要重写的父类方法toString,按回车键,但是该方法体中默认依然调用父类中的方法,则需要手动编写需要实现功能的代码
/*@Override
public String toString() {
return "车牌号:" + this.id + ",品牌:" + this.brand + ",颜色:" + this.color + ",价格:" + this.price;
}*/
@Override
public String toString() {
return "Car{" +
"id='" + id + '\'' +
", brand='" + brand + '\'' +
", color='" + color + '\'' +
", price=" + price +
'}';
}
}
package com.jian.demo7;
public class Test {
public static void main(String[] args) {
//创建车对象
Car c = new Car();
/*
通过运行得到:
1.当只输出对象名c时,则输出:com.jian.demo7.Car@4554617c
也就是输出:完整类名@十六进制数
2.原因:
在java中,当只输出对象名时,系统默认调用toString()方法
也就是说c 等价于编写c.toString()
当前对象名c是Car类型,因此在输出对象名c时,先在Car类中找toString()方法,如果没有找到则再去父类Object类中找,因此目前对象名c也就是调用Object类中的toString方法
Object类中的toSring方法体:getClass().getName() + "@" + Integer.toHexString(hashCode());
3.练习:当只输出对象名时,则输出该对象中所有的属性值
4.解决办法:
使用toString方法完成
而toString方法是Object类中的,但是Object类中的方法不能满足子类的需求,则需要在子类中重写父类的toString方法
第一种方式:光标放在子类中,按Ctrl + O选择要重写的父类方法toString,按回车键,但是该方法体中默认依然调用父类中的方法,则需要手动编写需要实现功能的代码
第二种方式:光标放在子类中,按Alt + Insert键,选择要重写的toString方法,然后按回车键,选择要得到的实例变量的值,然后按回车键,则在方法体中自动生成代码 ,比较常用
5.其实使用第二种方式重写,类似于之前编写的print方法,来实现输出实例变量中的值
*/
System.out.println(c.toString()); //等价于c
c = new Car("京A12345", "大众", "白色", 120000);
System.out.println(c);
}
}