数据结构与算法分析-第一章Java类(02)
编写一个名为Person的类,它包含分别表示人的名字与年龄的两个数据域。要求此类包含对其中任何一个数据域进行设置与获取的方法。还要求包含可进行下列测试的方法:
- 两个Person对象是否相等--即是否有相同的名称与年龄
- 一个人是否比另一个人年长
写一个程序演示类的每一个方法
代码实现
package com.crazycoder2010.datastructure.ch01; public class Person { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public boolean equals(Object obj) { if(obj == null || !(obj instanceof Person)){ return false; } Person that = (Person)obj; boolean isAgeEquals = this.age == that.age; if(!isAgeEquals){ return false; } if(this.name == null){ if(that.name == null){ return true; }else{ return false; } }else{ return this.name.equals(that.name); } } public boolean isOlderThan(Person person){ return this.age > person.getAge(); } @Override public String toString() { return "name:"+this.name+",age:"+this.age; } }测试代码
package com.crazycoder2010.datastructure.ch01; public class PersonTest { public static void main(String[] args) { Person person = new Person(); person.setName("Kevin"); person.setAge(20); System.out.println(person); Person person2 = new Person(); person2.setName("Kevin"); person2.setAge(20); System.out.println(person.equals(person2));//true System.out.println(person.equals(new Person()));//false System.out.println(person.equals(null));//false Person person3 = new Person(); person3.setName("Kevin"); System.out.println(person.equals(person3));//false person3.setAge(28); System.out.println(person.isOlderThan(person3));//false } }执行输出结果
name:Kevin,age:20 true false false false false