vkapustin vkapustin - 7 months ago 14
Java Question

How to define a explicit constructor when the parent class doesn't have a default constructor?

I'm getting the following error in my code:


Implicit super constructor GLabel() is undefined for default
constructor. Must define an explicit constructor


My parent class "GLabel" is contained in an external jar. I can open the source file, but I can't make edits to it. So I decided to extend GLabel to create the functionality I want.

As you can see "GLabel" class does not have an empty constructor. I'm assuming this is what is causing the issue? How do I fix this?

Child Class

import acm.graphics.GLabel;

public class BreakoutLabels extends GLabel{

// no code inside

}


Parent Class

public class GLabel extends GObject
{

public static final Font DEFAULT_FONT = new Font("Default", 0, 12);

private String label;

private Font labelFont;

public GLabel(String str)
{
this(str, 0.0D, 0.0D);
}

public GLabel(String str, double x, double y)
{
label = str;
setFont(DEFAULT_FONT);
setLocation(x, y);
}
}

Answer

If GLabel doesn't have a default (empty-args) constructor, then your constructors for your derived class have to call one of the declared constructors for GLabel. However GLabel is defined means that a default constructor makes no sense, and you'll have to provide suitable arguments.

Comments