Why are abstract constructors allowed?

I am making an abstract Font

class and I want to force the subclasses to declare a constructor that takes one parameter int

(font size). I tried to do it in the following way.

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

      

It's not exactly the end of the world - it's not necessary, I just wanted the Java compiler to make me remember the implementation of this constructor. I'm just wondering why is this not allowed?

+3


source to share


3 answers


Any constructor created must be called by any class that implements this abstract class, so there is no need to "remind" people to implement this constructor.

There are many reasons why 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 is not your place to specify which constructors can and cannot use these classes.

+6


source


If you implement this constructor in an abstract class, at least at a trivial level (perhaps without error checking), give it secure access and make it so that the variable size

can only be set through it - this would effectively enforce its use by subclasses , assuming that size

is an important attribute.



0


source


You should check this: Can an abstract class have a constructor?

Try removing the abstract @ your constructor. It should be:

public Font(int size);

      

Should work then if I'm not mistaken :)

0


source







All Articles