Search code examples
javalibgdx

Why is my class not a BitmapFont if I am extending it


So I have this class:

public class Font extends BitmapFont
{
    FreeTypeFontGenerator generator;
    FreeTypeFontGenerator.FreeTypeFontParameter parameter;
    public Font()
    {
        generator = new FreeTypeFontGenerator();
        parameter = new FreeTypeFontGenerator.FreeTypeFontParameter();
        parameter.size = 30;
        parameter.color = Color.WHITE;
        this = generator.generateFont(parameter);
        generator.dispose();
    }
}

But on this line:

this = generator.generateFont(parameter);

I get an error, it says: required Font, found BitmapFont.

Now I dont get it why the compiler doesnt see my Font class as a BitmapFont. Do you guys know the reason and also know how I still can make the font assign to the class itself?


Solution

  • Regardless of the mistake that Raeffaele describes in the comments, you are not understanding a fundamental thing of OO here.

    Take this simple is-a example: a Cow is an Animal. But an Animal is not always a Cow. It can also be a Sheep, or a Dog. And as we all know, a Dog and a Cow are completely different, even though they both inherit from Animal.

    Now we apply that to your situation. A Font is-a BitmapFont, but a BitmapFont is not always a Font.

    Given that, The

    generator.generateFont(parameter);
    

    call returns a LibGDX BitmapFont instance, not an instance of your own Font class. So it would be a very bad idea to try and assign it to a variable that demands an instance of Font anyway.


    Shorter version.

    You should understand that this works because Font is-a BitmapFont:

    BitmapFont font = new Font();
    

    and this does not because BitmapFont is not a Font:

    Font font = new BitmapFont();
    

    Your code is attempting to create the second situation, just in a slightly different way.