Home > Software engineering >  Cannot create instance of type or interface
Cannot create instance of type or interface

Time:11-08

I am trying to get bug to work, but am having no luck, the parts marked as abstract need to stay that way seeing as it is specified as such in the question I am trying to answer.

    abstract class Worker
    {
        protected string name;
        protected int ID;
        protected abstract int expLevel(); // create abstract property for experience field
        public abstract string Experience(int expLevel); //create abstract method called experience

        
        public Worker(string name, int ID) //constructor for worker
        {
            this.name = name;
            this.ID = ID;
        }
        public Worker() { } // how I tried to fix error
    }

    class Labourer : Worker 
    {  
        Worker worker1 = new Worker(); // line in which bug occurs

        protected override int expLevel()
        {
            return expLevel();
        }

        public override string Experience(int expLevel) // returns strings to be used later
        {
            if (expLevel > 5)
            {
                return "Senior";
            }
            return "Junior";
        }

       
    }
}

CodePudding user response:

You can not create an instance of an abstract type (Worker). When you create a concrete type based on an abstract type, like you do in the Labourer class, you can create an instance of that type.

Labourer labourer = new Labourer();

I am not sure you what your intent is with the new Worker() but I can only guess.

Do you want to call the constructor of the Worker base class? You can do it like this:

class Labourer : Worker 
{
   public Labourer(string name, string id) : base(name, string)
   {
   }

 // rest of implementation
}  
       

CodePudding user response:

You should add a constructor in your derived class as well that calls the base-class one:

abstract class Worker
{
    protected string name;
    protected int ID;
    protected abstract int expLevel(); // create abstract property for experience field
    public abstract string Experience(int expLevel); //create abstract method called experience

    
    public Worker(string name, int ID) //constructor for worker
    {
        this.name = name;
        this.ID = ID;
    }
    // no need for a parameter-less ctor here
}

class Labourer : Worker 
{  
    public Labourer(string name, int ID) : base(name, id) { }

    protected override int expLevel()
    {
        return expLevel();
    }

    public override string Experience(int expLevel) // returns strings to be used later
    {
        if (expLevel > 5)
        {
            return "Senior";
        }
        return "Junior";
    } 
}

Now within your client-code you can instantiate a worker like this:

Worker worker = new Labourer("Me", 1);
  • Related