How to make a subclass implement an interface?

2019-07-19 05:40发布

问题:

I have already created a class and a subclass and have a bunch of code in both. I've created an interface in the parent class and I have no idea how to make my child class implement the interface :/

The code is:

class Car { 
              public interface ISmth
              {
                  void MyMethod();
              }
          }
class MyCar : Car { 
                      //implement the interface 
                  }

回答1:

This is how your code should probably be laid out.

public interface ISmth
{
    void MyMethod();
}

class Car
{
}

class MyCar : Car, ISmth
{
    public void MyMethod()
    {
    }
}

There doesn't seem to be a reason to nest ISmth in Car, but if you do have one you certainly could do it.



回答2:

You need to declare MyCar like that:

class MyCar: Car, Car.ISmth {}