Search code examples
javaconstructorimageicon

Java: error: cannot reference this before supertype constructor has been called


I'm trying to add a constructor to the javax.swing.ImageIcon. It shall resolve the directory structure to be able to access the ImageIcon class like a image map.

What I'm trying to do is:

public class CPImageIcon extends ImageIcon {

    public CPImageIcon(String name) {

        super(this.getClass().getResource("/desktopapplication1/resources/" + name), "description");
    }

but this leads to:

warning: [options] bootstrap class path not set in conjunction with -source 1.7
I:\DesktopApplication1\src\desktopapplication1\CPImageIcon.java:18: error: cannot reference this before supertype constructor has been called
        super(this.getClass().getResource("/desktopapplication1/resources/" + name),"");

If I try to super other constructors it works.


Solution

  • super constructor must be the first call in subclasses constructors. If ommitted it will call automatically to default constructor super().

    this represent the current instance, and can't be used before calling super.

    You could use the following approach, commented or uncommented:

    import javax.swing.*;
    
    public class CPImageIcon extends ImageIcon {
    
        public CPImageIcon(String name) {
            super(CPImageIcon.class.getResource("/desktopapplication1/resources/" + name), "description");
    //        super(Thread.currentThread().getContextClassLoader().getResource("/desktopapplication1/resources/" + name), "description");
        }
    }