代码如下:
MyExceptional1类:
package org.jsoft.zuoye;
public class MyExceptional1 extends Exception{//继承
public MyExceptional1(){//无参构造
super("Exception,即出现异常");//子类在构造自己的过程中先构造父类
}
public MyExceptional1(String s){//有参构造
super(s);//输出字符串的具体信息
}
public static void main(String[] args) {
try {//捕获
number(5);
} catch (MyExceptional1 e) {//处理
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void number(int num) throws MyExceptional1{//抛出异常
if(num<10){
throw new MyExceptional1("MyExceptional1,即出现自己的异常");//声明
}
}
运行结果:
MyExceptional2 类:
package org.jsoft.zuoye;
public class MyExceptional2 extends RuntimeException{//未检查异常
public MyExceptional2(){
super("Exception,即出现异常");
}
public MyExceptional2(String s){
super(s);
}
public static void main(String[] args) {
num(15);
}
public static void num(int n) throws MyExceptional2{//抛出异常
if(n>10){
throw new MyExceptional2("MyExceptional2,即出现自己的异常");//声明
}
}
}
运行结果:
2、比较是否为同一人
package org.jsoft.zuoye;
public class TestPerson {
public static void main(String[] args) {
Person p=new Person("张蕾");//实例化
Person p1=new Person("罗维璠");//实例化
System.out.println(p.equals(p1));
}
}
class Person{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Person(String name){
this.name=name;
}
@Override
public boolean equals(Object obj) {
// TODO Auto-generated method stub
if(obj==null){
return false;
}else{
if(obj instanceof Person ){
Person p =(Person)obj;
if(this.name.equals(p)){
return true;
}
}
}
return false;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return name;
}
}
运行结果: