Is it a right generalization association of an interface class

757 Views Asked by At

As the ttitle said, im asking if is this a good programmation/design way.

I got a class, that can be just an Interface (only got 1 abstract method and few attributes)

As a example of my case, this is similar:

We got a main class Car than could be a truck, auto, moto, ... and has an abstract method void move()

Could I design CAR as interface, and the other concrete classes as a generalization of CAR class? or is this wrong?

public interface Car{
  private int length;
  private float speed;

  public void move();
}

public class truck : Car{
  //Constructor
  public Car(int size)
  {
     length=size;
  }

  public void move()
  {
     //Move code
  }
}

and then

Car myCar = new truck();
myCar.move();

Would be right?

2

There are 2 best solutions below

1
On BEST ANSWER

You're mixing up the terms "abstract" and "interface" here.

It is perfectly fine to refer to an instance of a class by the interface it implements. Here you see an interface, ICookieFactory which bakes abstract Cookies:

public interface ICookieFactory 
{
    Cookie BakeCookie(); 
}

public class ChocolateChipCookieFactory : ICookieFactory
{
    public Cookie BakeCookie()
    {
        return new ChocolateChipCookie();
    }
}

public abstract class Cookie
{
    public abstract IEnumerable<Crumb> Crumble();
}

public class ChocolateChipCookie : Cookie
{
    public override IEnumerable<Crumb> Crumble()
    {
        ...
    }
}

ICookieFactory factory = new ChocolateChipCookieFactory();
Cookie cookie = factory.BakeCookie();
foreach (Crumb crumb in cookie.Crumble())
{
    ...
}

An interface tells implementations of it which methods or properties it must support, but cannot provide any implementation code itself. You can't define fields in an interface.

An abstract class can include any number of fields and methods, and abstract methods that must be overridden by child classes.

A single class can implement multiple interfaces but only inherit from a single abstract class.

0
On

As far as i Know, yes, its possible and right to create an interface which child classes would be a case of generalization association.

But in my case, and thanks to the only answer of C.Evenhuis, i realized it'll be better to make an abstract class (so i can combine some abstract methods that child classes must override, with some concrete methods that childs can override or simply use).