Search code examples
javaswingjframe

What does "Canonical constructor cannot delegate to another constructor" mean?


Im new to programming and following this tutorial for a weather gui app in java. Below is the very small amount of code I'm working with so far. Where I am getting errors is at the "super("Weather App");" line.

import javax.swing.*;

public class WeatherAppGui extends JFrame
{
    public WeatherAppGui
    {
        //GUI and title
        super("Weather App");

        //kill app on closure
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        //dimensions
        setSize(450, 650);

        //load gui to center screen
        setLocationRelativeTo(null);

        //manually position gui components
        setLayout(null);

        //no resizing
        setResizable(false);




    }
}

What is going on underneath the hood that is causing "Canonical constructor cannot delegate to another constructor"? If the super keyword means to reference a parent classes (JFrame in this situation) method and thats where the error is coming up at... then why is IntelliJ speaking of constructors if a constructor is something that basically just holds an objects attribute's (parameters) until the constructor is called when the object is created and the object gets its attributes(arguments) (in layman's terms).


Solution

  • A constructor should have a parameter list after the name of the class. You should write:

    public WeatherAppGui() {
        // ...
    }
    

    Note the parentheses after the name of the class. That is an empty parameter list.

    Without the parentheses, the compiler parses this as a canonical constructor, which is something that record classes can have, but is not allowed inside a regular class like WeatherAppGui. So the error message is a bit confusing.

    If you remove the super constructor call, "WeatherAppGui" would be highlighted red instead, and IntelliJ (not sure about other IDEs) would say "Parameter list expected", which is a much more useful error message.