casting parent to child - BufferedImage object

Kirill Kulakov picture Kirill Kulakov · Aug 3, 2012 · Viewed 24.3k times · Source

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

W. Goeman picture W. Goeman · Aug 3, 2012

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..