我知道下面的赋值给出了运行时错误,我知道原因:
Sub sb = (Sub) new Super();
public class Super {
//class members
}
public class Sub extends Super{
//class members
}
但是当我们覆盖javax.swng.JPanel的protected void paintComponent(Graphics g)
方法(在Graphics2D extends Graphics
之后)时,为什么没有RuntimeError:
Graphics2D g2d = (Graphics2D)g;
是因为g中已经有Graphics2D
引用吗?
答案 0 :(得分:1)
这不是错误,因为正如您所说,g
实际上是由系统实例化的Graphics2D
对象(保持在Graphics2D
是Graphics
的子类)。
当你这样做时:
Sub sb = (Sub) new Super();
您明确地创建了超类的新对象。但是,当你这样做时:
Graphics2D g2d = (Graphics2D)g;
您没有创建新的Graphics2D对象,而是投射已经是Graphics2D
实例的现有对象。
在swing渲染的情况下,执行图形操作的对象是Graphics2D
对象,但paintComponent()
接收Graphics
对象以便向后兼容。
答案 1 :(得分:0)
没有运行时错误,因为它与你在方法中所做的不一样,这里发生的事情更像是这样:
public void doSomethingWithSuper(Super superObj) {
superObj.methodOfSuper();
}
public void doSomethinfWithSubThatCanResultInException(Super superObj) {
Sub sub = (Sub) superObj;
sub.methodOdSub();
}
Super subObj = new Sub();
Super superObj = new Super();
doSomethingWithSuper(subObj); //ok
doSomethingWithSuper(superObj); //ok
doSomethinfWithSubThatCanResultInException(subObj); // ok because the dynamic type of subObj is Sub therefore the cast is valid
doSomethinfWithSubThatCanResultInException(superObj); // exception because the dynamic type of superObj is super therefore the cast is not valid