0

I am stuck with a downcasting issue with java.

Here is the plot: The class MyPicture extends the abstract class BufferedImage. The point is to add a few methods to BufferedImage. Then, I have the class MyWindow which sets a user-friendly window. In this class, I want to load a picture in MyPic, copy it in MyPic_filtered, use a method used in MyPicture on MyPic_filtered and finally show MyPic and MyPic_filtered in separated windows (but this last part is OK ^^). I don't know which types I should use for MyPic and MyPic_filtered. I tried the cast them in the right type, it builds but doesn't run.

Here is the code:

//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();`

Could someone help me please?

Dmitry Gamolin
  • 934
  • 1
  • 12
  • 29
Peyret
  • 3
  • 1
  • 1
    `ImageIO.read()` doesn't return a `MyPicture`. You cannot magically turn an object into a type that it isn't. – SLaks Nov 21 '16 at 21:09
  • 1
    Also Java is case-sensitive, so `MyPic != myPic` – QBrute Nov 21 '16 at 21:11
  • *The class `MyPicture` extends the abstract class `BufferedImage`*... This statement is incorrect. `BufferedImage` isn't abstract. There's generally no need to extend it, and I would advice against it. Use delegation instead of inheritance. – Harald K Nov 22 '16 at 08:19

1 Answers1

0

You can add a caster when you are trying to pass a base class instance to extended one, like:

MyPicture myPic_filtered = (MyPicture)myPic; 

Then you can access "myPic" by using this keyword.


Or maybe you do not need to extend the BufferedImage. Just treat bufferedImage as an instance variable, like:

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

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

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

Not sure which structure is better. But it solves the problem in either way.