欢迎来到天天文库
浏览记录
ID:40579076
大小:33.88 KB
页数:32页
时间:2019-08-04
《thinkinginjava习题答案11》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、这是第12章的答案:Chapter12Exercise1//:c12:E01_Rhomboid.java//+MjavaE01_Rhomboid/******************Exercise1*******************AddRhomboidtoShapes.java.Createa*Rhomboid,upcastittoaShape,thendowncast*itbacktoaRhomboid.Trydowncastingtoa*Circleandseewhathappens.*****
2、******************************************/importjava.util.*;classShape{voiddraw(){System.out.println(this+".draw()");}}classCircleextendsShape{publicStringtoString(){return"Circle";}}classSquareextendsShape{publicStringtoString(){return"Square";}}classTri
3、angleextendsShape{publicStringtoString(){return"Triangle";}}classRhomboidextendsShape{publicStringtoString(){return"Rhomboid";}}publicclassE01_Rhomboid{publicstaticvoidmain(String[]args){Lists=newArrayList();s.add(newCircle());s.add(newSquare());s.add(newT
4、riangle());s.add(newRhomboid());Iteratore=s.iterator();while(e.hasNext())((Shape)e.next()).draw();//Upcasttoshape:Shapeshape=newRhomboid();//DowncasttoRhomboid:Rhomboidr=(Rhomboid)shape;//DowncasttoCircle.Succeedsat//compile-time,failsatruntimewith//aClass
5、CastException://!Circlec=(Circle)shape;}}///:~Theoutputis:Circle.draw()Square.draw()Triangle.draw()Rhomboid.draw()Exercise2//:c12:E02_Instanceof.java//+MjavaE02_Instanceof/******************Exercise2*******************ModifyExercise1sothatitusesinstanceof*
6、tocheckthetypebeforeperformingthe*downcast.***********************************************/publicclassE02_Instanceof{publicstaticvoidmain(String[]args){//Upcasttoshape:Shapeshape=newRhomboid();//DowncasttoRhomboid:Rhomboidr=(Rhomboid)shape;//TestbeforeDown
7、casting:Circlec=null;if(shapeinstanceofCircle)c=(Circle)shape;elseSystem.out.println("shapenotaCircle");}}///:~Theoutputis:shapenotaCircleExercise3//:c12:E03_Highlight.java//+MjavaE03_Highlight/******************Exercise3*******************ModifyShapes.jav
8、asothatitcan"highlight"*(setaflag)inallshapesofaparticular*type.ThetoString()methodforeachderived*ShapeshouldindicatewhetherthatShapeis*"highlighted."***********************************************/importjava
此文档下载收益归作者所有