Abstract Class Inheritance

Abstract classes are classes that cannot be instantiated. But in this lecture, Nathan makes a constructor for PlayerBaseState, which is an abstract class. Constructors can be called when we make an instance of a class.
So how does this work?

Hi @SEEMANTA_DEBDAS. Welcome to the community!

You are absolutely right that abstract classes cannot be instantiated, but the classes that inherit from them can. An abstract class’s constructor must be called by the inheriting class like this:

public abstract class BaseClass
{
    protected int number;
    public BaseClass(int number)
    {
        this.number = number;
    }
}

// inheriting class
public class SomeClass : BaseClass
{
    // needs to either provide it itself
    public SomeClass() : base(12) { } // base is calling the base class' constructor

    // or get it from somewhere
    public SomeClass(int number) : base(number) {}
}

You cannot successfully inherit an abstract class with a constructor without calling it from the inheriting class’s constructor.

Hope this clears things up

3 Likes

@bixarrio has the right of this one.

The reason it’s important that we have this parameter based constructor (and not a default parameter constructor) is that when we call create a new state, we want to ensure that the stateMachine value is set in the new state. By putting this in our abstract state constructor, we ensure that it is, indeed, set every time.

1 Like

@bixarrio @Brian_Trotter Thank you for your replies!

@bixarrio That’s what I thought! Thanks for clarifying. The example really helped.

@Brian_Trotter Clear and concise as always! Thank’s a lot

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms