Reputation:
I was watching a video (https://www.youtube.com/watch?v=Huj3Jbz-NFw) and here is a picture from it.
My question is: Couldn't class AB be created without using interfaces Such that you hold the A and B objects inside and call them? What information am I throwing away when I say that interface can be ignored.
Upvotes: 0
Views: 191
Reputation: 762
I think your question is why do we even need an interface.
One of the reasons I could think of is reducing the coupling between the classes. In Test driven development, interfaces help you lot to replace with mock objects.
Check these links for more information. Why do we need interfaces in Java? https://social.msdn.microsoft.com/Forums/vstudio/en-US/8edbf675-6375-4735-997e-bd7bce58f115/why-do-we-need-interfaces?forum=csharpgeneral
Upvotes: 0
Reputation: 5847
Yes, the AB
class could contain the A
and the B
objects as class members
.
The example in the image is kinda hard to picture in a 'real' example.
I ususaly go after the rule:
If it IS a [type], inherit.
If it HAS a [type], member.
Example.
Cat is an Animal, so Cat inherit from Animal.
Cat has a Tail, so Tail is a member of Cat.
And as C# do not let you inherit from multiple classes, you have to use interfaces.
Cat is an Animal, but it also is a Trickster, and thats two different types.
So it implements the IAnimal
and ITrickster
interfaces!
Upvotes: 0
Reputation: 4415
By implementing IA
and IB
class AB
can be used wherever IA
or IB
are expected:
void doSomethingWithIA(IA item)
{
item.AMethod();
}
...
AB ab = new AB();
doSomethingWithIA(ab);
If AB
had just the same Method names as IA
and IB
doSomethingWithIA()
would not accept it as argument.
Upvotes: 2