【问题标题】:Java: error: cannot reference this before supertype constructor has been calledJava:错误:在调用超类型构造函数之前无法引用 this
【发布时间】:2020-05-28 09:49:24
【问题描述】:

我正在尝试向javax.swing.ImageIcon 添加一个构造函数。它应该解析目录结构,以便能够像图像映射一样访问ImageIcon 类。

我想做的是:

public class CPImageIcon extends ImageIcon {

    public CPImageIcon(String name) {

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

但这会导致:

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),"");

如果我尝试超越其他构造函数,它会起作用。

【问题讨论】:

  • 你真的需要扩展ImageIcon吗?不能直接用工厂方法来构造ImageIcon的实例吗?

标签: java constructor imageicon


【解决方案1】:

super 构造函数必须是子类构造函数中的第一个调用。 如果省略,它将自动调用默认构造函数super()

this代表当前实例,在调用super之前不能使用。

您可以使用以下方法,已注释或未注释:

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");
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多