图片问题

Issue with downcasting Picture

我遇到了 java 的沮丧问题。

剧情如下: class MyPicture 扩展了摘要 class BufferedImage。重点是在BufferedImage中添加几个方法。然后,我有 class MyWindow 设置了一个用户友好的 window。在这个class中,我想在MyPic中加载一张图片,在MyPic_filtered中复制它,在MyPic_filtered上使用MyPicture中使用的方法,最后显示MyPicMyPic_filtered 分开 windows (但最后一部分没问题 ^^)。 我不知道 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();`

有人可以帮我吗?

当您尝试将基本 class 实例传递给扩展实例时,您可以添加一个施法者,例如:

MyPicture myPic_filtered = (MyPicture)myPic; 

然后您可以使用 this 关键字访问 "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
         ........
    }
}

不确定哪种结构更好。但它以任何一种方式解决了问题。