I am looking into some concepts of abstraction and was wondering if an abstract class should implement an interface directly or you should extend the class and implement intefaces in the subtype.
So in the example below:
interface Being{
alive:boolean;
}
abstract class Animal implements Being{
alive:boolean;
}
class Dog extends Animal{
bark(){
console.log("Bark");
}
}
class Earth{
beings:Being[];
}
The example can be rewritten like shown below:
interface Being{
alive:boolean;
}
abstract class Animal{
alive:boolean;
}
class Dog extends Animal implements Being{
bark(){
console.log("Bark");
}
}
class Earth{
beings:Being[];
}
My questions are:
Well I think you kind of gave the answer to yourself. The two examples represent different use cases, so I don't think there is a "better example".
Let's try to break it down into plain words.
First example you have an Being and all Animals definitively have the attribute "alive". This also counts for the Dog in this example.
In the second example however your Animal is not required to have the "alive" attribute. (Then the question is, if it really make sense to have it their). However the Dog again then implements the interface.
So if you say there is a possibility to have a Dog, that is an Animal but should not have the attribute "alive" (maybe it's a Zombie-Dog) you should put it on the Dog itself. But if you are going to implement all the fields/functions/logic into the Animal class anyway (and you don't care for Zombie-Dogs) you should put the interface on the Animal class.
So this is probably not the "clear" answer you were looking for. But it depends from case to case. You should always implement the Interface in the place where the according logic is. So if you want the alive logic to be on the animal put it there, if there can be animals that have no alive property, put it on the Dog itself.