简体   繁体   中英

oop interface, inheritance, base class,

I'm trying to learn interface and base classes on practical example. Let's say that I want to to abstract Player entity On Player.cs should be all common properties and methods for every sport in which player is assigned. So, there will be TeamSportPlayer, IndividualSportPlayer. Again, FootballPlayer would derive from TeamSportPlayer, TennisPlayer would derive from IndividualSportPlayer and so on. All this players should have access to first class Player and their properties.

Hope I'm not too confusing.

Question is: Is this proper way of abstracting player representation in terms of oop?

How would you do this on this practical example?

Abstract classes are used for defining objects that you are never going to have an instance of. Interfaces on the other hand are used to define behaviour of objects, and interfaces are independent from the inheritance hierarchy.

Using your sports example:

Player.cs can be an abstract class. It has fields that every player has like name, age, address, etc. But you never have a "Player" on the sports field, you have a "Football player" or a "Basketball player". And the classes FootballPlayer.cs and BasketballPlayer.cs inherit from the abstract class Player.cs.

Interface on the other hand defines some common behaviour that the classes share. Usually its used to define how other classes can interact with them. So for instance, if you have classes called TennisPlayer.cs , BasketballPlayer.cs and FootballPlayer.cs you can have an interface called IHasJerseyNumber.cs . Basketball and football players have jersey numbers so they would inherit the IHasJerseyNumber.cs interface. Tennis players don't have a number and they wont inherit the interface. A totally seperate class like Referee.cs can implement the interface as well, providing he too has a jersey number (possible in some sports).

You can read more here:

Interfaces

Abstract classes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM