java 中重写toString()方法,javatostring
分享于 点击 21706 次 点评:224
java 中重写toString()方法,javatostring
java 中重写toString()方法
toString()方法 一般出现在System.out.println(类名.toString());
toString()是一种自我描述方法 本身返回的是 getClass().getName() + "@" +Integer.toHexString(hashCode());
也就是 类名 + @ +hashCode的值
重写toString() 只会对类生效,并不能字符串生效; 例如
View Code
重写toString()对类生效
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
package
com.stu;
//用toString 重写一个类
public
class Car {
//成员变量
private
String carNo;
private
String carName;
private
String color;
private
double price;
//有参构造函数
Car(String carNo,String carName,String color, double
price){
this .carNo=carNo;
this .carName=carName;
this .color=color;
this .price=price;
}
//get set方法
public
String getCarNo(){
return
carNo;
}
public
void setCarNo(String carNo){
this .carNo=carNo;
}
public
String getCarName() {
return
carName;
}
public
void setCarName(String carName) {
this .carName = carName;
}
public
String getColor() {
return
color;
}
public
void setColor(String color) {
this .color = color;
}
public
double getPrice() {
return
price;
}
public
void setPrice( double
price) {
this .price = price;
}
//重写toString();
public
String toString(){
return
"这个汽车名叫 " +carName+ ",型号是 " +carNo+ ",汽车颜色 " +color+ ",价格
" +price;
}
public
static void
main(String[] args){
//创建一个Car的对象
Car myCar= new
Car( "苏A 4995" , "长安汽车" , "灰蓝色" , 70000.00 );
//类名开头字母大写
System.out.println(myCar.toString());
}
}
|
输出结果:
假如不对toString()进行重写则 输出结果:
com.stu.Car@2542880d ==> 类名 + “@” +hashCode值
2.为什么要重写toString()方法
在Object类里面定义toString()方法的时候返回的对象的哈希code码,这个hashcode码不能简单明了的表示出对象的属性。所以要重写toString()方法。
当需要将一个对象输出到显示器时,通常要调用他的toString()方法,将对象的内容转换为字符串.java中的所有类默认都有一个toString()方法。
默认情况下 System.out.println(对象名)或者System.out.println(对象名.toString())输出的是此对象的类名和此对象对应内存的首地址如果想自定义输出信息必须重写toString()方法。
相关文章
- 暂无相关文章
用户点评