问题描述
想法问一下,上次有许多朋友说的,父类对象不可以直接强制转换为子类对象如A类、B类,BextendsA的Aa=newA();Bb=newB();b=(B)a;//把父类对象强制转换为子类对象,编译无错,执行时出错。但是为什么书的Graphics对象强制转换为Graphics2D对象后才能在屏幕上画图或文本?Graphics2D类是Graphics类的子类,用来绘制2D图形,这句话的意思是把Graphics类的对象g,强制转换成Graphics2D类的对象g2d。importjava.awt.*;importjava.applet.*;importjava.awt.geom.*;importjava.util.*;publicclassRandomShapesextendsApplet{privateShapeshape;publicvoidinit(){shape=newRectangle2D.Double(-1.0,-1.0,1.0,1.0);}publicvoidpaint(Graphicsg){Graphics2Dg2d=(Graphics2D)g;//★★★这句话是什么意思,为什么有这样的用法?AffineTransformidentity=newAffineTransform();Randomrand=newRandom();intwidth=getSize().width;intheight=getSize().height;g2d.setColor(Color.BLACK);g2d.fillRect(0,0,width,height);for(intn=0;n<300;n++){g2d.setTransform(identity);g2d.translate(rand.nextInt()%width,rand.nextInt()%height);g2d.rotate(Math.toRadians(360*rand.nextDouble()));g2d.scale(60*rand.nextDouble(),60*rand.nextDouble());g2d.setColor(newColor(rand.nextInt()));g2d.fill(shape);}}}
解决方案
解决方案二:
请问,父类对象到底能不能转换为子类对象?
解决方案三:
还有那个在struts1.x中的execute()方法中的四个参数就有ActionFormform,在方法体中就要把form这个父类对象,强制转换为自己设计的myForm类,myFormmyform=(myForm)form;才能获得传递的提交表单数据。form是ActionForm来的,"RegForm也继承了ActionForm",一定要强制类型转换才行!这里父类对象强制转换为子类对象,为什么我们在直接写Aa=newA();Bb=newB();b=(B)a;就错了呢?