Inheritance and interfaces

2019-07-17 15:28发布

This is somewhat of a follow-up question to this question.

Suppose I have an inheritance tree as follows:

Car -> Ford -> Mustang -> MustangGT

Is there a benefit to defining interfaces for each of these classes? Example:

ICar -> IFord -> IMustang -> IMustangGT

I can see that maybe other classes (like Chevy) would want to implement Icar or IFord and maybe even IMustang, but probably not IMustangGT because it is so specific. Are the interfaces superfluous in this case?

Also, I would think that any class that would want to implement IFord would definitely want to use its one inheritance by inheriting from Ford so as not to duplicate code. If that is a given, what is the benefit of also implementing IFord?

14条回答
乱世女痞
2楼-- · 2019-07-17 16:12

I woudl create the first two levels, ICar and IFord and leave the second level alone until I need an interface at that second level.

查看更多
▲ chillily
3楼-- · 2019-07-17 16:22

Make an ICar and all the rest (Make=Ford, Model=Mustang, and stuff) as members of a class that implements the interface.

You might wanna have your Ford class and for example GM class and both implement ICar in order to use polymorphism if you don't wanna go down the route of checking Make == Whatever, that's up to your style.

Anyway - In my opinion those are attributes of a car not the other way around - you just need one interface because methods are common: Brake, SpeedUp, etc.

Can a Ford do stuff that other cars cannot? I don't think so.

查看更多
登录 后发表回答