为什么在paintComponent方法中为Graphics2D引用变量分配Graphics引用时没有运行时错误?

时间:2014-05-08 07:34:20

标签: java polymorphism

我知道下面的赋值给出了运行时错误,我知道原因:

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引用吗?

2 个答案:

答案 0 :(得分:1)

这不是错误,因为正如您所说,g实际上是由系统实例化的Graphics2D对象(保持在Graphics2DGraphics的子类)。

当你这样做时:

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