If I understand you correctly, your question is the following: since we use interfaces for code reusability, why they only have abstract methods? It makes no sense.
The answer is simple: interfaces are not for code reusability.
So why do we use them?
Suppose we have three classes: Dog
, Chicken
and Fish
. All of these extend the class Animal
. However, while Dog
and Chicken
can run, a Fish
can only swim.
class Dog extends Animal
{
void Run()
{
// how a dog runs
}
}
class Chicken extends Animal
{
void Run()
{
// how a chicken runs
}
}
class Fish extends Animal
{
void Swim()
{
// how a fish swims
}
}
Now I will ask you: is this code valid?
MakeAnimalRun(Animal animal)
{
animal.Run();
}
No, it isn't. While it is perfectly logical to invoke the Run()
method for a Dog
or a Chicken
, it doesn't make any sense to invoke it for a Fish
, since it can only swim.
To be able to call the animal's Run()
method, I need to make sure the animal can actually run.
That is where interfaces become handy. Interfaces are useful when we need to know for sure that an object has a specific behavior.
So let us create an interface called ICanRun
, and make all the animals that can run implement it:
interface ICanRun
{
void Run();
}
class Dog extends Animal implements ICanRun
{
void Run()
{
// how a dog runs.
}
}
class Chicken extends Animal implements ICanRun
{
void Run()
{
// how a chicken runs.
}
}
And now this code is perfectly valid since we know for sure that the animal can run:
void MakeAnimalRun(ICanRun animal)
{
animal.Run();
}
Notice that when I talk about a behavior, I only talk about the ability to do something, and not about how this ability is actually expressed. Both a Dog
and a Chicken
can run, but they run very differently: a Dog
uses 4 legs while a chicken uses only 2. So the implementation of the Run()
method for the Dog
will be very different from the implementation for the Chicken
. When I am defining this interface, I am concerned about "what can that animal do" and not about "how does it do it".
To summarize:
Interfaces are not for code reusability. Interfaces represent a behavior that an object has and do not care about how it implements this behavior. This allows us to know for sure that the object we deal with has the behavior we are looking for.