Why am I unable to use the setter method of a base class in a derived class

126 Views Asked by At

I've recently made a switch from Java to C# and I'm wondering why I'm unable to set the property of a derived class as shown in the example below:

public abstract class Vehicle
{
    private string name;

    public void setName(string name) 
    {
        this.name = name; 
    }
}

public class Car : Vehicle
{
    setName("Car")
}
2

There are 2 best solutions below

0
On BEST ANSWER

Your method can't be called directly in the class body, it has to be called from another method (the constructor for instance).

Try this:

public abstract class Vehicle
{
    private string name;

    public string getName()
    {
        return name;
    }

    public string setName(string name)
    {
        this.name = name; 
    }
}

public class Car : Vehicle
{
    public Car()
    {
        setName("Car");
    }
}
2
On

You need either an assignment call or another method to call setName. How is the compiler supposed to know when to execute this method call? Do this:

public class Car : Vehicle
{
    public string SetCarName()
    {
       base.setName();
    }
}