Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why aren't abstract constructors allowed?

Tags:

java

I'm making an abstract Font class and I want to force subclasses to declare a constructor that takes a single int parameter (font size). I tried doing so as follows.

public abstract class Font {
  ...
  public abstract Font(int size);
  ...
}

But my compiler declares:

Error:(20, 19) java: <path omitted>/Font.java:20: modifier abstract not allowed here

This isn't exactly the end of the world - this isn't strictly necessary, I just wanted the Java compiler to force me to remember to implement that constructor. I just wonder why this isn't allowed?

like image 997
Michael Dorst Avatar asked Oct 29 '25 15:10

Michael Dorst


1 Answers

Any constructor you create must be called by any class that implements this abstract class, so there's not really a need to "remind" people to implement that constructor.

There are a lot of reasons that people extending your classes might want to create their own constructors. For example:

public MySpecialSize16Font()
{
    super(16);
}

or

public ColoredFont(int size, Color color)
{
    super(size);
    this.color = color;
}

It's not really your place to specify what constructors these classes can and cannot provide.

like image 182
StriplingWarrior Avatar answered Nov 01 '25 05:11

StriplingWarrior