0

I was watching a video (https://www.youtube.com/watch?v=Huj3Jbz-NFw) and here is a picture from it.

enter image description here

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.

  • 2
    This is a common question when people first learn about interfaces. An interface is a contract, if you only have one object using the contract then its hard to see the value, but when you have hundreds its much easier. – crthompson Nov 25 '14 at 21:33
  • @paqogomez Do you know of any good resources that may illustrate this? Or are most scaled down as seen above? –  Nov 25 '14 at 21:42
  • Any good c# book will walk you through interfaces and discuss their merits. My experience is to just use them until you understand why they allow you to code better. – crthompson Nov 25 '14 at 21:44
  • @paqogomez thank you :) I will check out a textbook to see if it helps –  Nov 25 '14 at 21:49

3 Answers3

2

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.

Ozan
  • 4,345
  • 2
  • 23
  • 35
0

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!

Jite
  • 5,761
  • 2
  • 23
  • 37
  • Maybe I don't fully understand the IS and HAS relationships. What is the most important thing about an IS relationship? –  Nov 25 '14 at 21:47
  • 1
    "Cat is an Animal" -> Any Animal method or property applies to Cat. "Cat has a Tail" -> the methods and properties of Tail apply to part of Cat, but not all of Cat – davidc Nov 25 '14 at 23:53
0

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

Community
  • 1
  • 1
Ahuman
  • 752
  • 6
  • 18