MyException类
package org.jsoft.zy;
public class MyException extends Exception{
public MyException(){
super("是一个人");
}
public MyException(String str){
super(str);
}
}
People类
package org.jsoft.zy;
public class People {
private String name;
private int age;
private char sex;
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;
}
public char getSex() {
return sex;
}
public void setSex(char sex) {
this.sex = sex;
}
public People(){}
public People(String name,char sex,int age){
this.name=name;
this.sex=sex;
this.age=age;
}
public String toString(){
return name+sex+age;
}
public boolean equals(Object obj){
if(this.getClass()==obj.getClass()){
People p=(People)obj;
if(name==p.name&&sex==p.sex&&age==p.age){
return true;
}
}
return false;
}
}
Persion类
package org.jsoft.zy;
public class Persion {
private String name;
private int age;
private char sex;
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;
}
public char getSex() {
return sex;
}
public void setSex(char sex) {
this.sex = sex;
}
public Persion(){}
public Persion(String name,char sex,int age){
this.name=name;
this.sex=sex;
this.age=age;
}
public String toString(){
return name+sex+age;
}
}
TestPeople类
package org.jsoft.zy;
public class TestPeople {
public static void main(String[] args) {
People p1=new People("小明",'男',21);
People p2=new People("小明",'男',21);
People p3=new People("小华",'男',21);
Persion p4=new Persion("小明",'男',21);
if(p1.equals(p2)){
System.out.println("yes");
}
else{
System.out.println("No");
}
if(p1.equals(p3)){
System.out.println("yes");
}else{
System.out.println("No");
}
if(p1.equals(p4)){
System.out.println("yes");
}else{
System.out.println("No");
}
try {
isSame(p1,p2); //同类同人比较
} catch (MyException e) {
// TODO Auto-generated catch block
System.out.println(e.getMessage().toString());
}
try {
isSame(p1,p3); //同类同桌比较
} catch (MyException e) {
// TODO Auto-generated catch block
System.out.println(e.getMessage().toString());
}
try {
isSame(p1,p4); //不同类同人比较
} catch (MyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void isSame(People p1,People p2) throws MyException{
if(p1.equals(p2)){
throw new MyException();
}else{
System.out.println("不是一个人");
}
}
public static void isSame(People p1,Persion p2) throws MyException{
if(p1.equals(p2)){
throw new MyException("是一个人");
}else{
System.out.println("不是一个人");
}
}
}