Chinaunix首页 | 论坛 | 博客
  • 博客访问: 686282
  • 博文数量: 152
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1793
  • 用 户 组: 普通用户
  • 注册时间: 2013-09-12 12:26
个人简介

相信自己,只有不想做的,没有做不到的。

文章分类

全部博文(152)

文章存档

2021年(1)

2015年(2)

2014年(74)

2013年(75)

分类: Java

2014-08-10 12:21:09

目标:掌握通过父类中的toString()方法,通过自定义的toString()方法返回的字符串来表示对象的方法。

源文件:Person.java
package cn.com.Person;


public class Person {


String name;
int Age;
String Sex;





public void setName(String _name){
//name = _name;
this.name = _name;
}

public void setAge(int _Age){
//name = _name;
this.Age = _Age;
}
public void setSex(String _Sex){
//name = _name;
this.Sex = _Sex;
}

public String showName(){
return this.name;
}

public int showAge(){
return this.Age;
}



public String showSex(){
return this.Sex;
}



//覆盖toString()方法
public String toString(){
//return getClass()+"["+"姓名 = " +name+",年龄 = "+Age+",性别 = "+Sex+"]";
return "["+"姓名 = " +name+",年龄 = "+Age+",性别 = "+Sex+"]";
}
}

源文件:TestString.java

/*
 * author guojing
 * e-mail guo443193911@126.com
 * 
 */

package cn.com.Person;


public class TestPerson {


/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Person person = new Person();
person.setName("赵六");
person.setAge(30);
person.setSex("女");
System.out.println(person);
}


}


在这个类中,覆盖了父类(在这里是Object类)的toString()方法,返回用以表示对象的字符串,在这个类
中,按照惯例返回 ”类名[属性1 = 值1,属性2 = 值 2] “ 格式的字符串作为表示类的字符串
编译运行结果如下:
[姓名 = 赵六,年龄 = 30,性别 = 女]



阅读(2637) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~