首页 > 代码库 > java练习题
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+"\t"+"age="+age; } } class A{}
java练习题
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。