Kirill Kulakov Kirill Kulakov - 5 months ago 20
Java Question

casting parent to child - BufferedImage object

I'm get a

ClassCastException
whenever I try to cast a BufferedImage (parent) to an AdvancedBufferedImage (child) which I extended myself, I've not overridden any methods and I've implemented all the contractors without modifying them

I'm gettign this exception whenever I try to create an AdvancedBufferedImage out of File using ImageIO.read() method.

File file = new file(path);
AdvancedBufferedImage image = (AdvancedBufferedImage) ImageIO.read(file);


It seems there should not be any problem, What could be the problem?

Answer

Downcasting like this is not allowed.

The preferred solution would be to create a constructor of AdvancedBufferedImage, taking a BufferedImage as parameter. With that you could do the following.

File file = new file(path);
AdvancedBufferedImage image = new AdvancedBufferedImage(ImageIO.read(file));

Here the constructor of AdvancedBufferedImage can decide how to properly convert a BufferedImage in an advanced one..

Comments