Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 541
Kirill Kulakov Avatar asked Aug 03 '12 15:08

Kirill Kulakov


2 Answers

downcast is allowed, but it must a actual instance of the child:

class A {
  String name = "a";
  A(){};
}

class B extends A {
}

public class Main {
  public static void main(String[] args) {
    A a = new B(); // must a b instance
    B b = new B();
    b = (B)a;
    System.out.println(b.name);

  }
}
like image 91
jamlee Avatar answered Sep 21 '22 22:09

jamlee


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

like image 22
W. Goeman Avatar answered Sep 18 '22 22:09

W. Goeman