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.

4
  • 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. Commented Nov 25, 2014 at 21:33
  • @paqogomez Do you know of any good resources that may illustrate this? Or are most scaled down as seen above? Commented Nov 25, 2014 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. Commented Nov 25, 2014 at 21:44
  • @paqogomez thank you :) I will check out a textbook to see if it helps Commented Nov 25, 2014 at 21:49

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I see the value in that. Thank you
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!

2 Comments

Maybe I don't fully understand the IS and HAS relationships. What is the most important thing about an IS relationship?
"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
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

1 Comment

The second link helped immensely. Thank you so much

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.