首先我们来看下JDK1.6所有父类Object中的toString方法是怎么描述的:
————————————————————————
toString
public String toString()
返回该对象的字符串表示。通常,toString 方法会返回一个“以文本方式表示”此对象的字符串。结果应是一个简明但易于读懂的信息表达式。建议所有子类都重写此方法。
Object 类的 toString 方法返回一个字符串,该字符串由类名(对象是该类的一个实例)、at 标记符“@”和此对象哈希码的无符号十六进制表示组成。换句话说,该方法返回一个字符串,它的值等于:
getClass().getName() + '@' + Integer.toHexString(hashCode())
——————
返回:
该对象的字符串表示形式。
————————————————————————
从API文档中可以了解到Object.toString方法(JVM中自带的)是返回一长串字符串即地址(cn.com.zxjy.oo.jdbc.project.vo.UserVo@15db9742
),而不是你想要的原始数据,所以怎么输出类中的原始数据呢?
下面我给你举个简单的例子:
public class UserVo { private String userId; private String password; private String userType; public UserVo(String userId, String password, String userType) { super(); this.userId = userId; this.password = password; this.userType = userType; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getUserType() { return userType; } public void setUserType(String userType) { this.userType = userType; } /*public String toString() { return userId + " " + password + " " + userType; }*/
public static void main(String args[]) { UserVo vo = new UserVo("zx001", "赵克德", "中层主管"); System.out.println(vo.toString()); } }
(文中绿色字体表示重写的toString 方法)
重写toString方法结果:
zx001 赵克德 中层主管
未重写toString方法(调用Object中方法)结果:
cn.com.zxjy.oo.jdbc.project.vo.UserVo@15db9742
在User类中 如果不实现重写toString方法(覆盖原Object中的toString方法),则主方法中将自动调用Objec中的toString方 法,将输出的是User类中的地址(cn.com.zxjy.oo.jdbc.project.vo.UserVo@15db9742);
而如果在User类中重写上面的toString方法(覆盖原Object中的toString方法),则主方法中调用重写的toString方法,输出类中原本的数据(zx001 赵克德 中层主管);
所以如果想要输出原来类中的数据而不是类中的地址,就需要在类中重写toString方法,达到覆盖Object超类中的toString方法的目的。
转发请标明原稿出处:https://www.cnblogs.com/amoszha/p/10894895.html