java练习题

1、异常类

public class Exception3{
    public static void main(String [] args){
        /**老师带电脑上课
        1、电脑类(蓝屏异常,冒烟异常)
        2、老师类*/
        Teacher t1 = new Teacher("王老师");
        try{
            t1.speak();
        }catch(NoPlanException e){
            System.out.println(e.toString());
            System.out.println("换人");
        }
    }
}
class Teacher{
    private String name;
    Compertor comp;
    Teacher(String name){
        this.name=name;
        comp = new Compertor();
    }
    public void speak() throws NoPlanException{
        try{
            comp.run();
            System.out.println(name+"讲课");
        }catch(LanPingException e){
            System.out.println(e.toString());
            comp.reset();
            speak();
        }catch(MaoYanException e){
            System.out.println(e.toString());
            test();
            throw new NoPlanException(e.getMessage()+"出现临时状况课程进行不下去");
        }
        
        
    }
        
    public void test(){
        System.out.println("大家开始练习");
    }
    
}
class Compertor{
    public static int type = 0;
    public void run()throws LanPingException,MaoYanException{
        System.out.println("电脑运行中....");
        if(type == 1){
            throw new LanPingException("电脑蓝屏了");
        }
        if(type == -1){
            throw new MaoYanException("电脑冒烟了");
        }
    }
    public void reset(){
        type = 0;
        System.out.println("电脑重启了....");
        
    }

}
class LanPingException extends Exception{
    LanPingException(String s){
        super(s);
    }
}
class MaoYanException extends Exception{
    MaoYanException(String s){
        super(s);
    }
}
class NoPlanException extends Exception{
    NoPlanException(String s){
        super(s);
    }
}

2、Object类常用方法

class ObjectDemo{
    public static void main(String[]args){
        Person p1 = new Person("notify",30);
        Person p2 = new Person("current",30);
        A a = new A();
        System.out.println(p1.equals(p2));
        System.out.println(p1.hashCode());
        System.out.println(p1.getClass().getName());
        System.out.println(p1.toString());
    }
}
class Person{
    private String name;
    private int age;
    Person(String name,int age){
        this.name=name;
        this.age=age;
    }
    public boolean equals(Object obj){
        if(!(obj instanceof Person)){
            throw new ClassCastException("类型转换异常,请传入人进行比较");
        }
        Person p = (Person)obj;
        return this.age==p.age;
    }
    public int hashCode(){
        return age;
    }
    public String toString(){
        return "name="+name+"	"+"age="+age;
    }
}
class A{}
原文地址:https://www.cnblogs.com/wangyinxu/p/6680781.html