2016-11-21 44 views
0

我堅持與java的向下轉換問題。問題與downcasting圖片

這是劇情: 類MyPicture擴展了抽象類BufferedImage。關鍵是要添加幾個方法到BufferedImage。然後,我有類MyWindow它設置了一個用戶友好的窗口。在本課中,我想加載MyPic中的圖片,將其複製到MyPic_filtered中,使用中的MyPicture中使用的方法,最後在分隔的窗口中顯示MyPicMyPic_filtered(但這最後一部分是OK ^^)。 我不知道我應該使用哪種類型的MyPicMyPic_filtered。我試圖將它們轉換爲正確的類型,但是它會生成但不會運行。

下面是代碼:

//Loading the picture 
BufferedImage MyPic = ImageIO.read(new File(URL)); //URL is a string 
//Copy the picture 
MyPicture myPic_filtered = myPic;    
//Use the method from MyPicture 
myPic_filtered.method_from_MyPicture();` 

有人能幫助我嗎?

+1

'ImageIO.read()'不返回'MyPicture'。你不能神奇地把一個物體變成一個不是的物體。 – SLaks

+1

另外Java是區分大小寫的,所以'MyPic!= myPic' – QBrute

+0

* MyPicture類擴展了抽象類BufferedImage * *這個語句是不正確的。 'BufferedImage'不是抽象的。通常不需要擴展它,我會建議反對它。使用委託而不是繼承。 – haraldK

回答

0

你可以當你試圖基類實例傳遞給一個延伸,像添加一個施法者:

MyPicture myPic_filtered = (MyPicture)myPic; 

然後你就可以使用這個關鍵字訪問「myPic」。


或者你也許不需要擴展BufferedImage。只需將bufferedImage作爲實例變量對待,如:

class MyPicture { 
    BufferedImage bi; 
    //other variables 
    ......; 

    public MyPicture(BufferedImage input) { 
      this.bi = input; 
    } 

    public BufferedImage method_from_MyPicture() { 
     //Do something with bi and output 
     ........ 
    } 
} 

不確定哪種結構更好。但它以任何方式解決了這個問題。