Search code examples
javaconstructorthisparentsuper

Define constant in relation to another constant in super class constructor


I'm trying to define a constant by a super() constructor. My problem is that I want to define it in relation to another constant of the same class. Let me show you my code. This is one of my child classes:

public class Ball extends DisplayedObject {

    public static String FILENAME = "/res/ball_icon.png";
    public BufferedImage IMAGE;

    public Ball() {
        super(this);
    } 
}

And this is the parent class:

public class DisplayedObject {

    public static String FILENAME;
    public BufferedImage IMAGE;

    public DisplayedObject(DisplayedObject obj) {
        InputStream is = getClass().getResourceAsStream(obj.FILENAME);
        try {
            obj.IMAGE = ImageIO.read(is);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("Error: Can't read image.");
        }
    }
}

I know it's not possible to call super() with this as a parameter because the object isn't defined at this point. But this is exactly my problem. How can I solve this in a short way?


Solution

  • You can pass the filename to the constructor of the super class :

    public Ball() {
        super(FILENAME);
    }
    

    And move the IMAGE member to the super-class :

    public class DisplayedObject
    {
        public BufferedImage IMAGE;
        ...
        public DisplayedObject(String filename) {
            InputStream is = getClass().getResourceAsStream(filename);
            try {
                IMAGE = ImageIO.read(is);
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("Error: Can't read image.");
            }
        }
    }
    

    BTW, IMAGE is not a constant.