Why would I want to use Interfaces? [closed]

2019-01-01 15:23发布

I understand that they force you to implement methods and such but what I cant understand is why you would want to use them. Can anybody give me a good example or explanation on why I would want to implement this.

标签: oop interface
20条回答
笑指拈花
2楼-- · 2019-01-01 15:59

As you noted, interfaces are good for when you want to force someone to make it in a certain format.

Interfaces are good when data not being in a certain format can mean making dangerous assumptions in your code.

For example, at the moment I'm writing an application that will transform data from one format in to another. I want to force them to place those fields in so I know they will exist and will have a greater chance of being properly implemented. I don't care if another version comes out and it doesn't compile for them because it's more likely that data is required anyways.

Interfaces are rarely used because of this, since usually you can make assumptions or don't really require the data to do what you need to do.

查看更多
爱死公子算了
3楼-- · 2019-01-01 16:02

The pedals on a car implement an interface. I'm from the US where we drive on the right side of the road. Our steering wheels are on the left side of the car. The pedals for a manual transmission from left to right are clutch -> brake -> accelerator. When I went to Ireland, the driving is reversed. Cars' steering wheels are on the right and they drive on the left side of the road... but the pedals, ah the pedals... they implemented the same interface... all three pedals were in the same order... so even if the class was different and the network that class operated on was different, i was still comfortable with the pedal interface. My brain was able to call my muscles on this car just like every other car.

Think of the numerous non-programming interfaces we can't live without. Then answer your own question.

查看更多
登录 后发表回答