簡體   English   中英

在paintComponent方法中將Graphics引用分配給Graphics2D引用變量時,為什么沒有運行時錯誤?

[英]why is there not a Runtime error when assigning Graphics reference to Graphics2D reference variable in paintComponent method?

我知道下面的賦值給出了運行時錯誤,我知道為什么:

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引用了嗎?

這是不是一個錯誤,因為正如你說, g真是Graphics2D通過系統實例化對象(請明Graphics2D是的子類Graphics )。

當您這樣做時:

Sub sb = (Sub) new Super();

您在顯式地創建超類的新對象。 但是,當您這樣做時:

Graphics2D g2d = (Graphics2D)g;

您不是在創建新的Graphics2D對象,而是在投射一個已經是Graphics2D實例的現有對象。

對於swing渲染,執行圖形操作的對象是Graphics2D對象,但是paintComponent()接收Graphics對象是為了向后兼容。

沒有運行時錯誤,因為它與您在方法中所做的操作不同,此處發生的情況更像是這樣:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM