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?
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 Cookie
s:
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.